From c58d109f0e8ce93a91879499e16d364a11462a19 Mon Sep 17 00:00:00 2001 From: Manuel Mauro Date: Sun, 23 Apr 2023 09:45:23 +0200 Subject: [PATCH] Add autogenerated algod client (#213) * Add autogenerated algod client * Fix test.env * Migrate health_check to new client * Migrate get_status to new client * Add error logging * Remove logging and add a message to the error * Use u64 for integers in algonaut_algod * Use byteslices in place of PathBuf * Integrate algod autogenerated client * Make it compile * Make the examples compile * Fix genesis hash ser-de * Fix example app_create * Fix part of the examples - app_call - app_clear_state - app_optin - app_update * Fix some examples * make tests compile * Remove algod models from algonaut_model * Fix de-ser-ialization of binary data * Minor fixes * Re-export ServiceError in the root of the crate * Rename ServiceError to Error * Add Block type alias * Rename algod_exp to openapi_algod * Refactor workspace * Re-export new crates * Format code * Clippy * Fix tests * Rename Algod methods * Fix tests --- .../workflows/{quickstart.yml => general.yml} | 12 +- Cargo.toml | 27 +- algonaut_algod/.gitignore | 3 + algonaut_algod/.openapi-generator-ignore | 23 + algonaut_algod/.openapi-generator/FILES | 128 + algonaut_algod/.openapi-generator/VERSION | 1 + algonaut_algod/.travis.yml | 1 + algonaut_algod/Cargo.toml | 21 + algonaut_algod/README.md | 183 ++ algonaut_algod/git_push.sh | 57 + algonaut_algod/src/apis/common_api.rs | 328 +++ algonaut_algod/src/apis/configuration.rs | 49 + algonaut_algod/src/apis/data_api.rs | 258 ++ algonaut_algod/src/apis/experimental_api.rs | 135 ++ algonaut_algod/src/apis/mod.rs | 103 + .../src/apis/nonparticipating_api.rs | 1455 +++++++++++ algonaut_algod/src/apis/participating_api.rs | 587 +++++ algonaut_algod/src/apis/private_api.rs | 497 ++++ algonaut_algod/src/apis/public_api.rs | 2157 +++++++++++++++++ algonaut_algod/src/lib.rs | 10 + .../src/models/abort_catchup_200_response.rs | 25 + algonaut_algod/src/models/account.rs | 151 ++ ...nt_application_information_200_response.rs | 30 + .../account_asset_information_200_response.rs | 30 + .../src/models/account_participation.rs | 55 + .../src/models/account_state_delta.rs | 27 + .../add_participation_key_200_response.rs | 22 + algonaut_algod/src/models/application.rs | 30 + .../src/models/application_local_state.rs | 34 + .../src/models/application_params.rs | 61 + .../src/models/application_state_schema.rs | 31 + algonaut_algod/src/models/asset.rs | 30 + algonaut_algod/src/models/asset_holding.rs | 35 + algonaut_algod/src/models/asset_params.rs | 90 + algonaut_algod/src/models/box_descriptor.rs | 27 + algonaut_algod/src/models/build_version.rs | 45 + algonaut_algod/src/models/dryrun_request.rs | 57 + algonaut_algod/src/models/dryrun_source.rs | 39 + algonaut_algod/src/models/dryrun_state.rs | 41 + .../src/models/dryrun_txn_result.rs | 66 + algonaut_algod/src/models/error_response.rs | 29 + algonaut_algod/src/models/eval_delta.rs | 35 + .../src/models/eval_delta_key_value.rs | 29 + .../get_application_boxes_200_response.rs | 21 + .../src/models/get_block_200_response.rs | 25 + .../src/models/get_block_hash_200_response.rs | 22 + ...ng_transactions_by_address_200_response.rs | 34 + .../src/models/get_status_200_response.rs | 170 ++ .../src/models/get_supply_200_response.rs | 35 + .../src/models/get_sync_round_200_response.rs | 22 + .../get_transaction_proof_200_response.rs | 63 + algonaut_algod/src/models/kv_delta.rs | 33 + .../src/models/light_block_header_proof.rs | 37 + algonaut_algod/src/models/mod.rs | 104 + algonaut_algod/src/models/model_box.rs | 30 + .../src/models/participation_key.rs | 67 + .../models/pending_transaction_response.rs | 84 + .../models/raw_transaction_200_response.rs | 22 + algonaut_algod/src/models/simulate_request.rs | 25 + .../simulate_request_transaction_group.rs | 25 + .../simulate_transaction_200_response.rs | 41 + .../simulate_transaction_group_result.rs | 48 + .../src/models/simulate_transaction_result.rs | 44 + .../src/models/start_catchup_200_response.rs | 25 + algonaut_algod/src/models/state_proof.rs | 32 + .../src/models/state_proof_message.rs | 51 + .../src/models/teal_compile_200_response.rs | 32 + .../models/teal_disassemble_200_response.rs | 22 + .../src/models/teal_dryrun_200_response.rs | 34 + algonaut_algod/src/models/teal_key_value.rs | 29 + algonaut_algod/src/models/teal_value.rs | 41 + .../models/transaction_params_200_response.rs | 56 + algonaut_algod/src/models/version.rs | 42 + algonaut_client/src/algod/v2/mod.rs | 406 ---- algonaut_client/src/indexer/mod.rs | 1 - algonaut_crypto/src/lib.rs | 15 +- algonaut_encoding/src/lib.rs | 20 +- algonaut_indexer/Cargo.toml | 38 + algonaut_indexer/README.md | 3 + .../sample.env | 0 .../src/error.rs | 0 .../src/extensions/mod.rs | 0 .../src/extensions/reqwest.rs | 0 .../src/indexer}/mod.rs | 0 .../src/indexer/v2/mod.rs | 0 .../src/lib.rs | 4 - .../src/token.rs | 0 {algonaut_client => algonaut_kmd}/Cargo.toml | 19 +- {algonaut_client => algonaut_kmd}/README.md | 2 +- algonaut_kmd/sample.env | 9 + algonaut_kmd/src/error.rs | 98 + algonaut_kmd/src/extensions/mod.rs | 1 + algonaut_kmd/src/extensions/reqwest.rs | 67 + .../src/kmd/mod.rs | 0 .../src/kmd/v1/mod.rs | 0 algonaut_kmd/src/lib.rs | 10 + algonaut_kmd/src/token.rs | 24 + algonaut_model/src/algod/mod.rs | 1 - algonaut_model/src/algod/v2/mod.rs | 956 -------- algonaut_model/src/lib.rs | 1 - algonaut_model/src/transaction.rs | 4 +- algonaut_transaction/Cargo.toml | 18 +- algonaut_transaction/src/builder.rs | 64 +- algonaut_transaction/src/transaction.rs | 8 +- examples/algod_client.rs | 3 +- examples/app_call.rs | 7 +- examples/app_clear_state.rs | 8 +- examples/app_close_out.rs | 7 +- examples/app_create.rs | 19 +- examples/app_delete.rs | 4 +- examples/app_optin.rs | 7 +- examples/app_update.rs | 8 +- examples/asset_clawback.rs | 4 +- examples/asset_create.rs | 11 +- examples/asset_optin.rs | 6 +- examples/asset_transfer.rs | 6 +- examples/atomic_swap.rs | 6 +- examples/key_reg.rs | 10 +- examples/kmd_sign_submit_transaction.rs | 6 +- examples/logic_sig_contract_account.rs | 7 +- examples/logic_sig_delegated.rs | 7 +- examples/logic_sig_delegated_multi.rs | 7 +- examples/multi_sig.rs | 4 +- examples/payment.rs | 4 +- examples/quickstart.rs | 2 +- examples/rekey.rs | 15 +- examples/sign_offline.rs | 2 +- examples/submit_file.rs | 2 +- src/algod/v2/error.rs | 17 + src/algod/v2/mod.rs | 585 +++-- src/atomic_transaction_composer/mod.rs | 119 +- src/error.rs | 88 +- src/indexer/v2/mod.rs | 37 +- src/kmd/v1/mod.rs | 55 +- src/lib.rs | 12 +- src/util/dryrun_printer.rs | 105 +- src/util/wait_for_pending_tx.rs | 9 +- test.env | 35 +- tests/step_defs/integration/abi.rs | 38 +- tests/step_defs/integration/applications.rs | 49 +- tests/step_defs/integration/general.rs | 12 +- tests/step_defs/integration/world.rs | 5 +- tests/step_defs/util.rs | 11 +- tests/test_algod_v2.rs | 368 --- tests/test_indexer_v2.rs | 305 --- tests/test_kmd_v1.rs | 679 ------ tests/test_transactions.rs | 137 -- 147 files changed, 9444 insertions(+), 3523 deletions(-) rename .github/workflows/{quickstart.yml => general.yml} (91%) create mode 100644 algonaut_algod/.gitignore create mode 100644 algonaut_algod/.openapi-generator-ignore create mode 100644 algonaut_algod/.openapi-generator/FILES create mode 100644 algonaut_algod/.openapi-generator/VERSION create mode 100644 algonaut_algod/.travis.yml create mode 100644 algonaut_algod/Cargo.toml create mode 100644 algonaut_algod/README.md create mode 100644 algonaut_algod/git_push.sh create mode 100644 algonaut_algod/src/apis/common_api.rs create mode 100644 algonaut_algod/src/apis/configuration.rs create mode 100644 algonaut_algod/src/apis/data_api.rs create mode 100644 algonaut_algod/src/apis/experimental_api.rs create mode 100644 algonaut_algod/src/apis/mod.rs create mode 100644 algonaut_algod/src/apis/nonparticipating_api.rs create mode 100644 algonaut_algod/src/apis/participating_api.rs create mode 100644 algonaut_algod/src/apis/private_api.rs create mode 100644 algonaut_algod/src/apis/public_api.rs create mode 100644 algonaut_algod/src/lib.rs create mode 100644 algonaut_algod/src/models/abort_catchup_200_response.rs create mode 100644 algonaut_algod/src/models/account.rs create mode 100644 algonaut_algod/src/models/account_application_information_200_response.rs create mode 100644 algonaut_algod/src/models/account_asset_information_200_response.rs create mode 100644 algonaut_algod/src/models/account_participation.rs create mode 100644 algonaut_algod/src/models/account_state_delta.rs create mode 100644 algonaut_algod/src/models/add_participation_key_200_response.rs create mode 100644 algonaut_algod/src/models/application.rs create mode 100644 algonaut_algod/src/models/application_local_state.rs create mode 100644 algonaut_algod/src/models/application_params.rs create mode 100644 algonaut_algod/src/models/application_state_schema.rs create mode 100644 algonaut_algod/src/models/asset.rs create mode 100644 algonaut_algod/src/models/asset_holding.rs create mode 100644 algonaut_algod/src/models/asset_params.rs create mode 100644 algonaut_algod/src/models/box_descriptor.rs create mode 100644 algonaut_algod/src/models/build_version.rs create mode 100644 algonaut_algod/src/models/dryrun_request.rs create mode 100644 algonaut_algod/src/models/dryrun_source.rs create mode 100644 algonaut_algod/src/models/dryrun_state.rs create mode 100644 algonaut_algod/src/models/dryrun_txn_result.rs create mode 100644 algonaut_algod/src/models/error_response.rs create mode 100644 algonaut_algod/src/models/eval_delta.rs create mode 100644 algonaut_algod/src/models/eval_delta_key_value.rs create mode 100644 algonaut_algod/src/models/get_application_boxes_200_response.rs create mode 100644 algonaut_algod/src/models/get_block_200_response.rs create mode 100644 algonaut_algod/src/models/get_block_hash_200_response.rs create mode 100644 algonaut_algod/src/models/get_pending_transactions_by_address_200_response.rs create mode 100644 algonaut_algod/src/models/get_status_200_response.rs create mode 100644 algonaut_algod/src/models/get_supply_200_response.rs create mode 100644 algonaut_algod/src/models/get_sync_round_200_response.rs create mode 100644 algonaut_algod/src/models/get_transaction_proof_200_response.rs create mode 100644 algonaut_algod/src/models/kv_delta.rs create mode 100644 algonaut_algod/src/models/light_block_header_proof.rs create mode 100644 algonaut_algod/src/models/mod.rs create mode 100644 algonaut_algod/src/models/model_box.rs create mode 100644 algonaut_algod/src/models/participation_key.rs create mode 100644 algonaut_algod/src/models/pending_transaction_response.rs create mode 100644 algonaut_algod/src/models/raw_transaction_200_response.rs create mode 100644 algonaut_algod/src/models/simulate_request.rs create mode 100644 algonaut_algod/src/models/simulate_request_transaction_group.rs create mode 100644 algonaut_algod/src/models/simulate_transaction_200_response.rs create mode 100644 algonaut_algod/src/models/simulate_transaction_group_result.rs create mode 100644 algonaut_algod/src/models/simulate_transaction_result.rs create mode 100644 algonaut_algod/src/models/start_catchup_200_response.rs create mode 100644 algonaut_algod/src/models/state_proof.rs create mode 100644 algonaut_algod/src/models/state_proof_message.rs create mode 100644 algonaut_algod/src/models/teal_compile_200_response.rs create mode 100644 algonaut_algod/src/models/teal_disassemble_200_response.rs create mode 100644 algonaut_algod/src/models/teal_dryrun_200_response.rs create mode 100644 algonaut_algod/src/models/teal_key_value.rs create mode 100644 algonaut_algod/src/models/teal_value.rs create mode 100644 algonaut_algod/src/models/transaction_params_200_response.rs create mode 100644 algonaut_algod/src/models/version.rs delete mode 100644 algonaut_client/src/algod/v2/mod.rs delete mode 100644 algonaut_client/src/indexer/mod.rs create mode 100644 algonaut_indexer/Cargo.toml create mode 100644 algonaut_indexer/README.md rename {algonaut_client => algonaut_indexer}/sample.env (100%) rename {algonaut_client => algonaut_indexer}/src/error.rs (100%) rename {algonaut_client => algonaut_indexer}/src/extensions/mod.rs (100%) rename {algonaut_client => algonaut_indexer}/src/extensions/reqwest.rs (100%) rename {algonaut_client/src/algod => algonaut_indexer/src/indexer}/mod.rs (100%) rename {algonaut_client => algonaut_indexer}/src/indexer/v2/mod.rs (100%) rename {algonaut_client => algonaut_indexer}/src/lib.rs (67%) rename {algonaut_client => algonaut_indexer}/src/token.rs (100%) rename {algonaut_client => algonaut_kmd}/Cargo.toml (54%) rename {algonaut_client => algonaut_kmd}/README.md (82%) create mode 100644 algonaut_kmd/sample.env create mode 100644 algonaut_kmd/src/error.rs create mode 100644 algonaut_kmd/src/extensions/mod.rs create mode 100644 algonaut_kmd/src/extensions/reqwest.rs rename {algonaut_client => algonaut_kmd}/src/kmd/mod.rs (100%) rename {algonaut_client => algonaut_kmd}/src/kmd/v1/mod.rs (100%) create mode 100644 algonaut_kmd/src/lib.rs create mode 100644 algonaut_kmd/src/token.rs delete mode 100644 algonaut_model/src/algod/mod.rs delete mode 100644 algonaut_model/src/algod/v2/mod.rs create mode 100644 src/algod/v2/error.rs delete mode 100644 tests/test_algod_v2.rs delete mode 100644 tests/test_indexer_v2.rs delete mode 100644 tests/test_kmd_v1.rs delete mode 100644 tests/test_transactions.rs diff --git a/.github/workflows/quickstart.yml b/.github/workflows/general.yml similarity index 91% rename from .github/workflows/quickstart.yml rename to .github/workflows/general.yml index 69da34e4..d69ecf06 100644 --- a/.github/workflows/quickstart.yml +++ b/.github/workflows/general.yml @@ -7,7 +7,7 @@ name: Continuous integration jobs: check: - name: Check + name: cargo-check runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 @@ -22,7 +22,7 @@ jobs: - uses: actions-rs/cargo@v1 wasm-check: - name: Check WASM + name: cargo-check-wasm runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 @@ -38,7 +38,7 @@ jobs: args: --target wasm32-unknown-unknown tests: - name: Tests + name: cargo-test runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 @@ -50,10 +50,10 @@ jobs: - uses: actions-rs/cargo@v1 with: command: test - args: --workspace --lib --examples --test test_logic_signature + args: --workspace --lib --examples --tests fmt: - name: Rustfmt + name: cargo-fmt runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 @@ -69,7 +69,7 @@ jobs: args: --all -- --check clippy: - name: Clippy + name: cargo-clippy runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 diff --git a/Cargo.toml b/Cargo.toml index 4c9e15ef..5e03127e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,33 +13,39 @@ version = "0.4.2" [workspace] members = [ - "algonaut_client", + "algonaut_algod", "algonaut_model", "algonaut_core", "algonaut_crypto", "algonaut_encoding", + "algonaut_indexer", + "algonaut_kmd", "algonaut_transaction", "algonaut_abi", ] [dependencies] -algonaut_client = { path = "algonaut_client", version = "0.4.2", default-features = false } +algonaut_algod = { path = "algonaut_algod", version = "0.4.2" } algonaut_model = { path = "algonaut_model", version = "0.4.2" } algonaut_core = { path = "algonaut_core", version = "0.4.2" } algonaut_crypto = { path = "algonaut_crypto", version = "0.4.2" } algonaut_encoding = { path = "algonaut_encoding", version = "0.4.2" } +algonaut_indexer = { path = "algonaut_indexer", version = "0.4.2", default-features = false } +algonaut_kmd = { path = "algonaut_kmd", version = "0.4.2", default-features = false } algonaut_transaction = { path = "algonaut_transaction", version = "0.4.2" } algonaut_abi = { path = "algonaut_abi", version = "0.4.2" } -log = "0.4.0" +data-encoding = "2.3.1" env_logger = "0.10.0" -thiserror = "1.0.23" -rmp-serde = "1.0.0" -num-traits = "0.2.14" -num-bigint = "0.4.3" futures-timer = "3.0.2" instant = { version = "0.1", features = ["now"] } -data-encoding = "2.3.1" +log = "0.4.0" +num-bigint = "0.4.3" +num-traits = "0.2.14" +reqwest = "0.11.16" +rmp-serde = "1.0.0" +serde_json = "1.0.0" sha2 = "0.10.1" +thiserror = "1.0.23" [target.'cfg(target_arch = "wasm32")'.dependencies] gloo-timers = { version = "0.2.4", features = ["futures"] } @@ -55,10 +61,11 @@ async-trait = "0.1.51" [features] default = ["native"] -native = ["algonaut_client/native"] -rustls = ["algonaut_client/rustls"] +native = ["algonaut_indexer/native", "algonaut_kmd/native"] +rustls = ["algonaut_indexer/rustls", "algonaut_indexer/rustls"] [[test]] name = "features_runner" # Allows Cucumber to print output instead of libtest harness = false +test = false diff --git a/algonaut_algod/.gitignore b/algonaut_algod/.gitignore new file mode 100644 index 00000000..6aa10640 --- /dev/null +++ b/algonaut_algod/.gitignore @@ -0,0 +1,3 @@ +/target/ +**/*.rs.bk +Cargo.lock diff --git a/algonaut_algod/.openapi-generator-ignore b/algonaut_algod/.openapi-generator-ignore new file mode 100644 index 00000000..7484ee59 --- /dev/null +++ b/algonaut_algod/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/algonaut_algod/.openapi-generator/FILES b/algonaut_algod/.openapi-generator/FILES new file mode 100644 index 00000000..b6e7bc88 --- /dev/null +++ b/algonaut_algod/.openapi-generator/FILES @@ -0,0 +1,128 @@ +.gitignore +.openapi-generator-ignore +.travis.yml +Cargo.toml +README.md +docs/AbortCatchup200Response.md +docs/Account.md +docs/AccountApplicationInformation200Response.md +docs/AccountAssetInformation200Response.md +docs/AccountParticipation.md +docs/AccountStateDelta.md +docs/AddParticipationKey200Response.md +docs/Application.md +docs/ApplicationLocalState.md +docs/ApplicationParams.md +docs/ApplicationStateSchema.md +docs/Asset.md +docs/AssetHolding.md +docs/AssetParams.md +docs/Box.md +docs/BoxDescriptor.md +docs/BuildVersion.md +docs/CommonApi.md +docs/DataApi.md +docs/DryrunRequest.md +docs/DryrunSource.md +docs/DryrunState.md +docs/DryrunTxnResult.md +docs/ErrorResponse.md +docs/EvalDelta.md +docs/EvalDeltaKeyValue.md +docs/ExperimentalApi.md +docs/GetApplicationBoxes200Response.md +docs/GetBlock200Response.md +docs/GetBlockHash200Response.md +docs/GetPendingTransactionsByAddress200Response.md +docs/GetStatus200Response.md +docs/GetSupply200Response.md +docs/GetSyncRound200Response.md +docs/GetTransactionProof200Response.md +docs/KvDelta.md +docs/LightBlockHeaderProof.md +docs/NonparticipatingApi.md +docs/ParticipatingApi.md +docs/ParticipationKey.md +docs/PendingTransactionResponse.md +docs/PrivateApi.md +docs/PublicApi.md +docs/RawTransaction200Response.md +docs/SimulateRequest.md +docs/SimulateRequestTransactionGroup.md +docs/SimulateTransaction200Response.md +docs/SimulateTransactionGroupResult.md +docs/SimulateTransactionResult.md +docs/StartCatchup200Response.md +docs/StateProof.md +docs/StateProofMessage.md +docs/TealCompile200Response.md +docs/TealDisassemble200Response.md +docs/TealDryrun200Response.md +docs/TealKeyValue.md +docs/TealValue.md +docs/TransactionParams200Response.md +docs/Version.md +git_push.sh +src/apis/common_api.rs +src/apis/configuration.rs +src/apis/data_api.rs +src/apis/experimental_api.rs +src/apis/mod.rs +src/apis/nonparticipating_api.rs +src/apis/participating_api.rs +src/apis/private_api.rs +src/apis/public_api.rs +src/lib.rs +src/models/abort_catchup_200_response.rs +src/models/account.rs +src/models/account_application_information_200_response.rs +src/models/account_asset_information_200_response.rs +src/models/account_participation.rs +src/models/account_state_delta.rs +src/models/add_participation_key_200_response.rs +src/models/application.rs +src/models/application_local_state.rs +src/models/application_params.rs +src/models/application_state_schema.rs +src/models/asset.rs +src/models/asset_holding.rs +src/models/asset_params.rs +src/models/box_descriptor.rs +src/models/build_version.rs +src/models/dryrun_request.rs +src/models/dryrun_source.rs +src/models/dryrun_state.rs +src/models/dryrun_txn_result.rs +src/models/error_response.rs +src/models/eval_delta.rs +src/models/eval_delta_key_value.rs +src/models/get_application_boxes_200_response.rs +src/models/get_block_200_response.rs +src/models/get_block_hash_200_response.rs +src/models/get_pending_transactions_by_address_200_response.rs +src/models/get_status_200_response.rs +src/models/get_supply_200_response.rs +src/models/get_sync_round_200_response.rs +src/models/get_transaction_proof_200_response.rs +src/models/kv_delta.rs +src/models/light_block_header_proof.rs +src/models/mod.rs +src/models/model_box.rs +src/models/participation_key.rs +src/models/pending_transaction_response.rs +src/models/raw_transaction_200_response.rs +src/models/simulate_request.rs +src/models/simulate_request_transaction_group.rs +src/models/simulate_transaction_200_response.rs +src/models/simulate_transaction_group_result.rs +src/models/simulate_transaction_result.rs +src/models/start_catchup_200_response.rs +src/models/state_proof.rs +src/models/state_proof_message.rs +src/models/teal_compile_200_response.rs +src/models/teal_disassemble_200_response.rs +src/models/teal_dryrun_200_response.rs +src/models/teal_key_value.rs +src/models/teal_value.rs +src/models/transaction_params_200_response.rs +src/models/version.rs diff --git a/algonaut_algod/.openapi-generator/VERSION b/algonaut_algod/.openapi-generator/VERSION new file mode 100644 index 00000000..ba8a874d --- /dev/null +++ b/algonaut_algod/.openapi-generator/VERSION @@ -0,0 +1 @@ +6.6.0-SNAPSHOT \ No newline at end of file diff --git a/algonaut_algod/.travis.yml b/algonaut_algod/.travis.yml new file mode 100644 index 00000000..22761ba7 --- /dev/null +++ b/algonaut_algod/.travis.yml @@ -0,0 +1 @@ +language: rust diff --git a/algonaut_algod/Cargo.toml b/algonaut_algod/Cargo.toml new file mode 100644 index 00000000..ac772459 --- /dev/null +++ b/algonaut_algod/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "algonaut_algod" +version = "0.4.2" +authors = ["contact@algorand.com"] +description = "API endpoint for algod operations." +# Override this license by providing a License Object in the OpenAPI. +license = "MIT" +edition = "2018" + +[dependencies] +algonaut_crypto = { path = "../algonaut_crypto", version = "0.4.2" } +algonaut_encoding = { path = "../algonaut_encoding", version = "0.4.2" } +algonaut_model = { path = "../algonaut_model", version = "0.4.2" } +serde = "^1.0" +serde_derive = "^1.0" +serde_json = "^1.0" +url = "^2.2" +uuid = { version = "^1.0", features = ["serde"] } +[dependencies.reqwest] +version = "^0.11" +features = ["json", "multipart"] diff --git a/algonaut_algod/README.md b/algonaut_algod/README.md new file mode 100644 index 00000000..1470e6de --- /dev/null +++ b/algonaut_algod/README.md @@ -0,0 +1,183 @@ +# Rust API client for openapi + +API endpoint for algod operations. + +For more information, please visit [https://www.algorand.com/get-in-touch/contact](https://www.algorand.com/get-in-touch/contact) + +## Overview + +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://openapis.org) from a remote server, you can easily generate an API client. + +- API version: 0.0.1 +- Package version: 0.0.1 +- Build package: `org.openapitools.codegen.languages.RustClientCodegen` + +## Installation + +Put the package under your project folder in a directory named `openapi` and add the following to `Cargo.toml` under `[dependencies]`: + +``` +openapi = { path = "./openapi" } +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://localhost* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*CommonApi* | [**get_genesis**](docs/CommonApi.md#get_genesis) | **GET** /genesis | Gets the genesis information. +*CommonApi* | [**get_ready**](docs/CommonApi.md#get_ready) | **GET** /ready | Returns OK if healthy and fully caught up. +*CommonApi* | [**get_version**](docs/CommonApi.md#get_version) | **GET** /versions | +*CommonApi* | [**health_check**](docs/CommonApi.md#health_check) | **GET** /health | Returns OK if healthy. +*CommonApi* | [**metrics**](docs/CommonApi.md#metrics) | **GET** /metrics | Return metrics about algod functioning. +*CommonApi* | [**swagger_json**](docs/CommonApi.md#swagger_json) | **GET** /swagger.json | Gets the current swagger spec. +*DataApi* | [**get_ledger_state_delta**](docs/DataApi.md#get_ledger_state_delta) | **GET** /v2/deltas/{round} | Get a LedgerStateDelta object for a given round +*DataApi* | [**get_sync_round**](docs/DataApi.md#get_sync_round) | **GET** /v2/ledger/sync | Returns the minimum sync round the ledger is keeping in cache. +*DataApi* | [**set_sync_round**](docs/DataApi.md#set_sync_round) | **POST** /v2/ledger/sync/{round} | Given a round, tells the ledger to keep that round in its cache. +*DataApi* | [**unset_sync_round**](docs/DataApi.md#unset_sync_round) | **DELETE** /v2/ledger/sync | Removes minimum sync round restriction from the ledger. +*ExperimentalApi* | [**experimental_check**](docs/ExperimentalApi.md#experimental_check) | **GET** /v2/experimental | Returns OK if experimental API is enabled. +*ExperimentalApi* | [**get_ledger_state_delta**](docs/ExperimentalApi.md#get_ledger_state_delta) | **GET** /v2/deltas/{round} | Get a LedgerStateDelta object for a given round +*NonparticipatingApi* | [**abort_catchup**](docs/NonparticipatingApi.md#abort_catchup) | **DELETE** /v2/catchup/{catchpoint} | Aborts a catchpoint catchup. +*NonparticipatingApi* | [**account_application_information**](docs/NonparticipatingApi.md#account_application_information) | **GET** /v2/accounts/{address}/applications/{application-id} | Get account information about a given app. +*NonparticipatingApi* | [**account_asset_information**](docs/NonparticipatingApi.md#account_asset_information) | **GET** /v2/accounts/{address}/assets/{asset-id} | Get account information about a given asset. +*NonparticipatingApi* | [**account_information**](docs/NonparticipatingApi.md#account_information) | **GET** /v2/accounts/{address} | Get account information. +*NonparticipatingApi* | [**get_application_box_by_name**](docs/NonparticipatingApi.md#get_application_box_by_name) | **GET** /v2/applications/{application-id}/box | Get box information for a given application. +*NonparticipatingApi* | [**get_application_boxes**](docs/NonparticipatingApi.md#get_application_boxes) | **GET** /v2/applications/{application-id}/boxes | Get all box names for a given application. +*NonparticipatingApi* | [**get_application_by_id**](docs/NonparticipatingApi.md#get_application_by_id) | **GET** /v2/applications/{application-id} | Get application information. +*NonparticipatingApi* | [**get_asset_by_id**](docs/NonparticipatingApi.md#get_asset_by_id) | **GET** /v2/assets/{asset-id} | Get asset information. +*NonparticipatingApi* | [**get_block**](docs/NonparticipatingApi.md#get_block) | **GET** /v2/blocks/{round} | Get the block for the given round. +*NonparticipatingApi* | [**get_block_hash**](docs/NonparticipatingApi.md#get_block_hash) | **GET** /v2/blocks/{round}/hash | Get the block hash for the block on the given round. +*NonparticipatingApi* | [**get_light_block_header_proof**](docs/NonparticipatingApi.md#get_light_block_header_proof) | **GET** /v2/blocks/{round}/lightheader/proof | Gets a proof for a given light block header inside a state proof commitment +*NonparticipatingApi* | [**get_state_proof**](docs/NonparticipatingApi.md#get_state_proof) | **GET** /v2/stateproofs/{round} | Get a state proof that covers a given round +*NonparticipatingApi* | [**get_status**](docs/NonparticipatingApi.md#get_status) | **GET** /v2/status | Gets the current node status. +*NonparticipatingApi* | [**get_supply**](docs/NonparticipatingApi.md#get_supply) | **GET** /v2/ledger/supply | Get the current supply reported by the ledger. +*NonparticipatingApi* | [**get_transaction_proof**](docs/NonparticipatingApi.md#get_transaction_proof) | **GET** /v2/blocks/{round}/transactions/{txid}/proof | Get a proof for a transaction in a block. +*NonparticipatingApi* | [**shutdown_node**](docs/NonparticipatingApi.md#shutdown_node) | **POST** /v2/shutdown | +*NonparticipatingApi* | [**simulate_transaction**](docs/NonparticipatingApi.md#simulate_transaction) | **POST** /v2/transactions/simulate | Simulates a raw transaction or transaction group as it would be evaluated on the network. The simulation will use blockchain state from the latest committed round. +*NonparticipatingApi* | [**start_catchup**](docs/NonparticipatingApi.md#start_catchup) | **POST** /v2/catchup/{catchpoint} | Starts a catchpoint catchup. +*NonparticipatingApi* | [**teal_compile**](docs/NonparticipatingApi.md#teal_compile) | **POST** /v2/teal/compile | Compile TEAL source code to binary, produce its hash +*NonparticipatingApi* | [**teal_disassemble**](docs/NonparticipatingApi.md#teal_disassemble) | **POST** /v2/teal/disassemble | Disassemble program bytes into the TEAL source code. +*NonparticipatingApi* | [**teal_dryrun**](docs/NonparticipatingApi.md#teal_dryrun) | **POST** /v2/teal/dryrun | Provide debugging information for a transaction (or group). +*NonparticipatingApi* | [**transaction_params**](docs/NonparticipatingApi.md#transaction_params) | **GET** /v2/transactions/params | Get parameters for constructing a new transaction +*NonparticipatingApi* | [**wait_for_block**](docs/NonparticipatingApi.md#wait_for_block) | **GET** /v2/status/wait-for-block-after/{round} | Gets the node status after waiting for a round after the given round. +*ParticipatingApi* | [**add_participation_key**](docs/ParticipatingApi.md#add_participation_key) | **POST** /v2/participation | Add a participation key to the node +*ParticipatingApi* | [**append_keys**](docs/ParticipatingApi.md#append_keys) | **POST** /v2/participation/{participation-id} | Append state proof keys to a participation key +*ParticipatingApi* | [**delete_participation_key_by_id**](docs/ParticipatingApi.md#delete_participation_key_by_id) | **DELETE** /v2/participation/{participation-id} | Delete a given participation key by ID +*ParticipatingApi* | [**get_participation_key_by_id**](docs/ParticipatingApi.md#get_participation_key_by_id) | **GET** /v2/participation/{participation-id} | Get participation key info given a participation ID +*ParticipatingApi* | [**get_participation_keys**](docs/ParticipatingApi.md#get_participation_keys) | **GET** /v2/participation | Return a list of participation keys +*ParticipatingApi* | [**get_pending_transactions**](docs/ParticipatingApi.md#get_pending_transactions) | **GET** /v2/transactions/pending | Get a list of unconfirmed transactions currently in the transaction pool. +*ParticipatingApi* | [**get_pending_transactions_by_address**](docs/ParticipatingApi.md#get_pending_transactions_by_address) | **GET** /v2/accounts/{address}/transactions/pending | Get a list of unconfirmed transactions currently in the transaction pool by address. +*ParticipatingApi* | [**pending_transaction_information**](docs/ParticipatingApi.md#pending_transaction_information) | **GET** /v2/transactions/pending/{txid} | Get a specific pending transaction. +*ParticipatingApi* | [**raw_transaction**](docs/ParticipatingApi.md#raw_transaction) | **POST** /v2/transactions | Broadcasts a raw transaction or transaction group to the network. +*PrivateApi* | [**abort_catchup**](docs/PrivateApi.md#abort_catchup) | **DELETE** /v2/catchup/{catchpoint} | Aborts a catchpoint catchup. +*PrivateApi* | [**add_participation_key**](docs/PrivateApi.md#add_participation_key) | **POST** /v2/participation | Add a participation key to the node +*PrivateApi* | [**append_keys**](docs/PrivateApi.md#append_keys) | **POST** /v2/participation/{participation-id} | Append state proof keys to a participation key +*PrivateApi* | [**delete_participation_key_by_id**](docs/PrivateApi.md#delete_participation_key_by_id) | **DELETE** /v2/participation/{participation-id} | Delete a given participation key by ID +*PrivateApi* | [**get_participation_key_by_id**](docs/PrivateApi.md#get_participation_key_by_id) | **GET** /v2/participation/{participation-id} | Get participation key info given a participation ID +*PrivateApi* | [**get_participation_keys**](docs/PrivateApi.md#get_participation_keys) | **GET** /v2/participation | Return a list of participation keys +*PrivateApi* | [**shutdown_node**](docs/PrivateApi.md#shutdown_node) | **POST** /v2/shutdown | +*PrivateApi* | [**start_catchup**](docs/PrivateApi.md#start_catchup) | **POST** /v2/catchup/{catchpoint} | Starts a catchpoint catchup. +*PublicApi* | [**account_application_information**](docs/PublicApi.md#account_application_information) | **GET** /v2/accounts/{address}/applications/{application-id} | Get account information about a given app. +*PublicApi* | [**account_asset_information**](docs/PublicApi.md#account_asset_information) | **GET** /v2/accounts/{address}/assets/{asset-id} | Get account information about a given asset. +*PublicApi* | [**account_information**](docs/PublicApi.md#account_information) | **GET** /v2/accounts/{address} | Get account information. +*PublicApi* | [**experimental_check**](docs/PublicApi.md#experimental_check) | **GET** /v2/experimental | Returns OK if experimental API is enabled. +*PublicApi* | [**get_application_box_by_name**](docs/PublicApi.md#get_application_box_by_name) | **GET** /v2/applications/{application-id}/box | Get box information for a given application. +*PublicApi* | [**get_application_boxes**](docs/PublicApi.md#get_application_boxes) | **GET** /v2/applications/{application-id}/boxes | Get all box names for a given application. +*PublicApi* | [**get_application_by_id**](docs/PublicApi.md#get_application_by_id) | **GET** /v2/applications/{application-id} | Get application information. +*PublicApi* | [**get_asset_by_id**](docs/PublicApi.md#get_asset_by_id) | **GET** /v2/assets/{asset-id} | Get asset information. +*PublicApi* | [**get_block**](docs/PublicApi.md#get_block) | **GET** /v2/blocks/{round} | Get the block for the given round. +*PublicApi* | [**get_block_hash**](docs/PublicApi.md#get_block_hash) | **GET** /v2/blocks/{round}/hash | Get the block hash for the block on the given round. +*PublicApi* | [**get_genesis**](docs/PublicApi.md#get_genesis) | **GET** /genesis | Gets the genesis information. +*PublicApi* | [**get_ledger_state_delta**](docs/PublicApi.md#get_ledger_state_delta) | **GET** /v2/deltas/{round} | Get a LedgerStateDelta object for a given round +*PublicApi* | [**get_light_block_header_proof**](docs/PublicApi.md#get_light_block_header_proof) | **GET** /v2/blocks/{round}/lightheader/proof | Gets a proof for a given light block header inside a state proof commitment +*PublicApi* | [**get_pending_transactions**](docs/PublicApi.md#get_pending_transactions) | **GET** /v2/transactions/pending | Get a list of unconfirmed transactions currently in the transaction pool. +*PublicApi* | [**get_pending_transactions_by_address**](docs/PublicApi.md#get_pending_transactions_by_address) | **GET** /v2/accounts/{address}/transactions/pending | Get a list of unconfirmed transactions currently in the transaction pool by address. +*PublicApi* | [**get_ready**](docs/PublicApi.md#get_ready) | **GET** /ready | Returns OK if healthy and fully caught up. +*PublicApi* | [**get_state_proof**](docs/PublicApi.md#get_state_proof) | **GET** /v2/stateproofs/{round} | Get a state proof that covers a given round +*PublicApi* | [**get_status**](docs/PublicApi.md#get_status) | **GET** /v2/status | Gets the current node status. +*PublicApi* | [**get_supply**](docs/PublicApi.md#get_supply) | **GET** /v2/ledger/supply | Get the current supply reported by the ledger. +*PublicApi* | [**get_sync_round**](docs/PublicApi.md#get_sync_round) | **GET** /v2/ledger/sync | Returns the minimum sync round the ledger is keeping in cache. +*PublicApi* | [**get_transaction_proof**](docs/PublicApi.md#get_transaction_proof) | **GET** /v2/blocks/{round}/transactions/{txid}/proof | Get a proof for a transaction in a block. +*PublicApi* | [**get_version**](docs/PublicApi.md#get_version) | **GET** /versions | +*PublicApi* | [**health_check**](docs/PublicApi.md#health_check) | **GET** /health | Returns OK if healthy. +*PublicApi* | [**metrics**](docs/PublicApi.md#metrics) | **GET** /metrics | Return metrics about algod functioning. +*PublicApi* | [**pending_transaction_information**](docs/PublicApi.md#pending_transaction_information) | **GET** /v2/transactions/pending/{txid} | Get a specific pending transaction. +*PublicApi* | [**raw_transaction**](docs/PublicApi.md#raw_transaction) | **POST** /v2/transactions | Broadcasts a raw transaction or transaction group to the network. +*PublicApi* | [**set_sync_round**](docs/PublicApi.md#set_sync_round) | **POST** /v2/ledger/sync/{round} | Given a round, tells the ledger to keep that round in its cache. +*PublicApi* | [**simulate_transaction**](docs/PublicApi.md#simulate_transaction) | **POST** /v2/transactions/simulate | Simulates a raw transaction or transaction group as it would be evaluated on the network. The simulation will use blockchain state from the latest committed round. +*PublicApi* | [**swagger_json**](docs/PublicApi.md#swagger_json) | **GET** /swagger.json | Gets the current swagger spec. +*PublicApi* | [**teal_compile**](docs/PublicApi.md#teal_compile) | **POST** /v2/teal/compile | Compile TEAL source code to binary, produce its hash +*PublicApi* | [**teal_disassemble**](docs/PublicApi.md#teal_disassemble) | **POST** /v2/teal/disassemble | Disassemble program bytes into the TEAL source code. +*PublicApi* | [**teal_dryrun**](docs/PublicApi.md#teal_dryrun) | **POST** /v2/teal/dryrun | Provide debugging information for a transaction (or group). +*PublicApi* | [**transaction_params**](docs/PublicApi.md#transaction_params) | **GET** /v2/transactions/params | Get parameters for constructing a new transaction +*PublicApi* | [**unset_sync_round**](docs/PublicApi.md#unset_sync_round) | **DELETE** /v2/ledger/sync | Removes minimum sync round restriction from the ledger. +*PublicApi* | [**wait_for_block**](docs/PublicApi.md#wait_for_block) | **GET** /v2/status/wait-for-block-after/{round} | Gets the node status after waiting for a round after the given round. + + +## Documentation For Models + + - [AbortCatchup200Response](docs/AbortCatchup200Response.md) + - [Account](docs/Account.md) + - [AccountApplicationInformation200Response](docs/AccountApplicationInformation200Response.md) + - [AccountAssetInformation200Response](docs/AccountAssetInformation200Response.md) + - [AccountParticipation](docs/AccountParticipation.md) + - [AccountStateDelta](docs/AccountStateDelta.md) + - [AddParticipationKey200Response](docs/AddParticipationKey200Response.md) + - [Application](docs/Application.md) + - [ApplicationLocalState](docs/ApplicationLocalState.md) + - [ApplicationParams](docs/ApplicationParams.md) + - [ApplicationStateSchema](docs/ApplicationStateSchema.md) + - [Asset](docs/Asset.md) + - [AssetHolding](docs/AssetHolding.md) + - [AssetParams](docs/AssetParams.md) + - [Box](docs/Box.md) + - [BoxDescriptor](docs/BoxDescriptor.md) + - [BuildVersion](docs/BuildVersion.md) + - [DryrunRequest](docs/DryrunRequest.md) + - [DryrunSource](docs/DryrunSource.md) + - [DryrunState](docs/DryrunState.md) + - [DryrunTxnResult](docs/DryrunTxnResult.md) + - [ErrorResponse](docs/ErrorResponse.md) + - [EvalDelta](docs/EvalDelta.md) + - [EvalDeltaKeyValue](docs/EvalDeltaKeyValue.md) + - [GetApplicationBoxes200Response](docs/GetApplicationBoxes200Response.md) + - [GetBlock200Response](docs/GetBlock200Response.md) + - [GetBlockHash200Response](docs/GetBlockHash200Response.md) + - [GetPendingTransactionsByAddress200Response](docs/GetPendingTransactionsByAddress200Response.md) + - [GetStatus200Response](docs/GetStatus200Response.md) + - [GetSupply200Response](docs/GetSupply200Response.md) + - [GetSyncRound200Response](docs/GetSyncRound200Response.md) + - [GetTransactionProof200Response](docs/GetTransactionProof200Response.md) + - [KvDelta](docs/KvDelta.md) + - [LightBlockHeaderProof](docs/LightBlockHeaderProof.md) + - [ParticipationKey](docs/ParticipationKey.md) + - [PendingTransactionResponse](docs/PendingTransactionResponse.md) + - [RawTransaction200Response](docs/RawTransaction200Response.md) + - [SimulateRequest](docs/SimulateRequest.md) + - [SimulateRequestTransactionGroup](docs/SimulateRequestTransactionGroup.md) + - [SimulateTransaction200Response](docs/SimulateTransaction200Response.md) + - [SimulateTransactionGroupResult](docs/SimulateTransactionGroupResult.md) + - [SimulateTransactionResult](docs/SimulateTransactionResult.md) + - [StartCatchup200Response](docs/StartCatchup200Response.md) + - [StateProof](docs/StateProof.md) + - [StateProofMessage](docs/StateProofMessage.md) + - [TealCompile200Response](docs/TealCompile200Response.md) + - [TealDisassemble200Response](docs/TealDisassemble200Response.md) + - [TealDryrun200Response](docs/TealDryrun200Response.md) + - [TealKeyValue](docs/TealKeyValue.md) + - [TealValue](docs/TealValue.md) + - [TransactionParams200Response](docs/TransactionParams200Response.md) + - [Version](docs/Version.md) + + +To get access to the crate's generated documentation, use: + +``` +cargo doc --open +``` + +## Author + +contact@algorand.com + diff --git a/algonaut_algod/git_push.sh b/algonaut_algod/git_push.sh new file mode 100644 index 00000000..f53a75d4 --- /dev/null +++ b/algonaut_algod/git_push.sh @@ -0,0 +1,57 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=$(git remote) +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/algonaut_algod/src/apis/common_api.rs b/algonaut_algod/src/apis/common_api.rs new file mode 100644 index 00000000..5ac808af --- /dev/null +++ b/algonaut_algod/src/apis/common_api.rs @@ -0,0 +1,328 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +use reqwest; + +use super::{configuration, Error}; +use crate::apis::ResponseContent; + +/// struct for typed errors of method [`get_genesis`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetGenesisError { + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_ready`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetReadyError { + Status500(), + Status503(), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_version`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetVersionError { + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`health_check`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum HealthCheckError { + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`metrics`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum MetricsError { + Status404(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`swagger_json`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum SwaggerJsonError { + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// Returns the entire genesis file in json. +pub async fn get_genesis( + configuration: &configuration::Configuration, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!("{}/genesis", local_var_configuration.base_path); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +pub async fn get_ready( + configuration: &configuration::Configuration, +) -> Result<(), Error> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!("{}/ready", local_var_configuration.base_path); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + Ok(()) + } else { + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Retrieves the supported API versions, binary build versions, and genesis information. +pub async fn get_version( + configuration: &configuration::Configuration, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!("{}/versions", local_var_configuration.base_path); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +pub async fn health_check( + configuration: &configuration::Configuration, +) -> Result<(), Error> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!("{}/health", local_var_configuration.base_path); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + Ok(()) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +pub async fn metrics( + configuration: &configuration::Configuration, +) -> Result<(), Error> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!("{}/metrics", local_var_configuration.base_path); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + Ok(()) + } else { + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Returns the entire swagger spec in json. +pub async fn swagger_json( + configuration: &configuration::Configuration, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!("{}/swagger.json", local_var_configuration.base_path); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} diff --git a/algonaut_algod/src/apis/configuration.rs b/algonaut_algod/src/apis/configuration.rs new file mode 100644 index 00000000..6c6dcc6a --- /dev/null +++ b/algonaut_algod/src/apis/configuration.rs @@ -0,0 +1,49 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +#[derive(Debug, Clone)] +pub struct Configuration { + pub base_path: String, + pub user_agent: Option, + pub client: reqwest::Client, + pub basic_auth: Option, + pub oauth_access_token: Option, + pub bearer_access_token: Option, + pub api_key: Option, + // TODO: take an oauth2 token source, similar to the go one +} + +pub type BasicAuth = (String, Option); + +#[derive(Debug, Clone)] +pub struct ApiKey { + pub prefix: Option, + pub key: String, +} + +impl Configuration { + pub fn new() -> Configuration { + Configuration::default() + } +} + +impl Default for Configuration { + fn default() -> Self { + Configuration { + base_path: "http://localhost".to_owned(), + user_agent: Some("OpenAPI-Generator/0.0.1/rust".to_owned()), + client: reqwest::Client::new(), + basic_auth: None, + oauth_access_token: None, + bearer_access_token: None, + api_key: None, + } + } +} diff --git a/algonaut_algod/src/apis/data_api.rs b/algonaut_algod/src/apis/data_api.rs new file mode 100644 index 00000000..26c275cb --- /dev/null +++ b/algonaut_algod/src/apis/data_api.rs @@ -0,0 +1,258 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +use reqwest; + +use super::{configuration, Error}; +use crate::apis::ResponseContent; + +/// struct for typed errors of method [`get_ledger_state_delta`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetLedgerStateDeltaError { + Status401(crate::models::ErrorResponse), + Status404(crate::models::ErrorResponse), + Status408(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + Status503(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_sync_round`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetSyncRoundError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + Status503(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`set_sync_round`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum SetSyncRoundError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + Status503(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`unset_sync_round`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum UnsetSyncRoundError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + Status503(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// Get ledger deltas for a round. +pub async fn get_ledger_state_delta( + configuration: &configuration::Configuration, + round: u64, + format: Option<&str>, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/deltas/{round}", + local_var_configuration.base_path, + round = round + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_str) = format { + local_var_req_builder = + local_var_req_builder.query(&[("format", &local_var_str.to_string())]); + } + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Gets the minimum sync round for the ledger. +pub async fn get_sync_round( + configuration: &configuration::Configuration, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!("{}/v2/ledger/sync", local_var_configuration.base_path); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Sets the minimum sync round on the ledger. +pub async fn set_sync_round( + configuration: &configuration::Configuration, + round: u64, +) -> Result<(), Error> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/ledger/sync/{round}", + local_var_configuration.base_path, + round = round + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + Ok(()) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Unset the ledger sync round. +pub async fn unset_sync_round( + configuration: &configuration::Configuration, +) -> Result<(), Error> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!("{}/v2/ledger/sync", local_var_configuration.base_path); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::DELETE, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + Ok(()) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} diff --git a/algonaut_algod/src/apis/experimental_api.rs b/algonaut_algod/src/apis/experimental_api.rs new file mode 100644 index 00000000..e913c90c --- /dev/null +++ b/algonaut_algod/src/apis/experimental_api.rs @@ -0,0 +1,135 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +use reqwest; + +use super::{configuration, Error}; +use crate::apis::ResponseContent; + +/// struct for typed errors of method [`experimental_check`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum ExperimentalCheckError { + Status404(), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_ledger_state_delta`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetLedgerStateDeltaError { + Status401(crate::models::ErrorResponse), + Status404(crate::models::ErrorResponse), + Status408(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + Status503(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +pub async fn experimental_check( + configuration: &configuration::Configuration, +) -> Result<(), Error> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!("{}/v2/experimental", local_var_configuration.base_path); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + Ok(()) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Get ledger deltas for a round. +pub async fn get_ledger_state_delta( + configuration: &configuration::Configuration, + round: u64, + format: Option<&str>, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/deltas/{round}", + local_var_configuration.base_path, + round = round + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_str) = format { + local_var_req_builder = + local_var_req_builder.query(&[("format", &local_var_str.to_string())]); + } + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} diff --git a/algonaut_algod/src/apis/mod.rs b/algonaut_algod/src/apis/mod.rs new file mode 100644 index 00000000..0b98deec --- /dev/null +++ b/algonaut_algod/src/apis/mod.rs @@ -0,0 +1,103 @@ +use std::error; +use std::fmt; + +#[derive(Debug, Clone)] +pub struct ResponseContent { + pub status: reqwest::StatusCode, + pub content: String, + pub entity: Option, +} + +#[derive(Debug)] +pub enum Error { + Reqwest(reqwest::Error), + Serde(serde_json::Error), + Io(std::io::Error), + ResponseError(ResponseContent), +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let (module, e) = match self { + Error::Reqwest(e) => ("reqwest", e.to_string()), + Error::Serde(e) => ("serde", e.to_string()), + Error::Io(e) => ("IO", e.to_string()), + Error::ResponseError(e) => ("response", format!("status code {}", e.status)), + }; + write!(f, "error in {}: {}", module, e) + } +} + +impl error::Error for Error { + fn source(&self) -> Option<&(dyn error::Error + 'static)> { + Some(match self { + Error::Reqwest(e) => e, + Error::Serde(e) => e, + Error::Io(e) => e, + Error::ResponseError(_) => return None, + }) + } +} + +impl From for Error { + fn from(e: reqwest::Error) -> Self { + Error::Reqwest(e) + } +} + +impl From for Error { + fn from(e: serde_json::Error) -> Self { + Error::Serde(e) + } +} + +impl From for Error { + fn from(e: std::io::Error) -> Self { + Error::Io(e) + } +} + +pub fn urlencode>(s: T) -> String { + ::url::form_urlencoded::byte_serialize(s.as_ref().as_bytes()).collect() +} + +pub fn parse_deep_object(prefix: &str, value: &serde_json::Value) -> Vec<(String, String)> { + if let serde_json::Value::Object(object) = value { + let mut params = vec![]; + + for (key, value) in object { + match value { + serde_json::Value::Object(_) => params.append(&mut parse_deep_object( + &format!("{}[{}]", prefix, key), + value, + )), + serde_json::Value::Array(array) => { + for (i, value) in array.iter().enumerate() { + params.append(&mut parse_deep_object( + &format!("{}[{}][{}]", prefix, key, i), + value, + )); + } + } + serde_json::Value::String(s) => { + params.push((format!("{}[{}]", prefix, key), s.clone())) + } + _ => params.push((format!("{}[{}]", prefix, key), value.to_string())), + } + } + + return params; + } + + unimplemented!("Only objects are supported with style=deepObject") +} + +pub mod common_api; +pub mod data_api; +pub mod experimental_api; +pub mod nonparticipating_api; +pub mod participating_api; +pub mod private_api; +pub mod public_api; + +pub mod configuration; diff --git a/algonaut_algod/src/apis/nonparticipating_api.rs b/algonaut_algod/src/apis/nonparticipating_api.rs new file mode 100644 index 00000000..033e82e1 --- /dev/null +++ b/algonaut_algod/src/apis/nonparticipating_api.rs @@ -0,0 +1,1455 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +use reqwest; + +use super::{configuration, Error}; +use crate::apis::ResponseContent; + +/// struct for typed errors of method [`abort_catchup`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum AbortCatchupError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`account_application_information`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum AccountApplicationInformationError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`account_asset_information`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum AccountAssetInformationError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`account_information`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum AccountInformationError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_application_box_by_name`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetApplicationBoxByNameError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status404(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_application_boxes`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetApplicationBoxesError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_application_by_id`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetApplicationByIdError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status404(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_asset_by_id`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetAssetByIdError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status404(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_block`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetBlockError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status404(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_block_hash`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetBlockHashError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status404(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_light_block_header_proof`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetLightBlockHeaderProofError { + Status401(crate::models::ErrorResponse), + Status404(crate::models::ErrorResponse), + Status408(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + Status503(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_state_proof`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetStateProofError { + Status401(crate::models::ErrorResponse), + Status404(crate::models::ErrorResponse), + Status408(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + Status503(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_status`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetStatusError { + Status401(crate::models::ErrorResponse), + Status500(String), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_supply`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetSupplyError { + Status401(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_transaction_proof`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetTransactionProofError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status404(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`shutdown_node`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum ShutdownNodeError { + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`simulate_transaction`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum SimulateTransactionError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + Status503(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`start_catchup`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum StartCatchupError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`teal_compile`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum TealCompileError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status404(), + Status500(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`teal_disassemble`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum TealDisassembleError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status404(), + Status500(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`teal_dryrun`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum TealDryrunError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status404(), + Status500(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`transaction_params`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum TransactionParamsError { + Status401(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + Status503(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`wait_for_block`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum WaitForBlockError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + Status503(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// Given a catchpoint, it aborts catching up to this catchpoint +pub async fn abort_catchup( + configuration: &configuration::Configuration, + catchpoint: &str, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/catchup/{catchpoint}", + local_var_configuration.base_path, + catchpoint = crate::apis::urlencode(catchpoint) + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::DELETE, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Given a specific account public key and application ID, this call returns the account's application local state and global state (AppLocalState and AppParams, if either exists). Global state will only be returned if the provided address is the application's creator. +pub async fn account_application_information( + configuration: &configuration::Configuration, + address: &str, + application_id: u64, + format: Option<&str>, +) -> Result< + crate::models::AccountApplicationInformation200Response, + Error, +> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/accounts/{address}/applications/{application_id}", + local_var_configuration.base_path, + address = crate::apis::urlencode(address), + application_id = application_id + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_str) = format { + local_var_req_builder = + local_var_req_builder.query(&[("format", &local_var_str.to_string())]); + } + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Given a specific account public key and asset ID, this call returns the account's asset holding and asset parameters (if either exist). Asset parameters will only be returned if the provided address is the asset's creator. +pub async fn account_asset_information( + configuration: &configuration::Configuration, + address: &str, + asset_id: u64, + format: Option<&str>, +) -> Result> +{ + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/accounts/{address}/assets/{asset_id}", + local_var_configuration.base_path, + address = crate::apis::urlencode(address), + asset_id = asset_id + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_str) = format { + local_var_req_builder = + local_var_req_builder.query(&[("format", &local_var_str.to_string())]); + } + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Given a specific account public key, this call returns the accounts status, balance and spendable amounts +pub async fn account_information( + configuration: &configuration::Configuration, + address: &str, + format: Option<&str>, + exclude: Option<&str>, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/accounts/{address}", + local_var_configuration.base_path, + address = crate::apis::urlencode(address) + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_str) = format { + local_var_req_builder = + local_var_req_builder.query(&[("format", &local_var_str.to_string())]); + } + if let Some(ref local_var_str) = exclude { + local_var_req_builder = + local_var_req_builder.query(&[("exclude", &local_var_str.to_string())]); + } + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Given an application ID and box name, it returns the box name and value (each base64 encoded). Box names must be in the goal app call arg encoding form 'encoding:value'. For ints, use the form 'int:1234'. For raw bytes, use the form 'b64:A=='. For printable strings, use the form 'str:hello'. For addresses, use the form 'addr:XYZ...'. +pub async fn get_application_box_by_name( + configuration: &configuration::Configuration, + application_id: u64, + name: &str, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/applications/{application_id}/box", + local_var_configuration.base_path, + application_id = application_id + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + local_var_req_builder = local_var_req_builder.query(&[("name", &name.to_string())]); + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Given an application ID, return all Box names. No particular ordering is guaranteed. Request fails when client or server-side configured limits prevent returning all Box names. +pub async fn get_application_boxes( + configuration: &configuration::Configuration, + application_id: u64, + max: Option, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/applications/{application_id}/boxes", + local_var_configuration.base_path, + application_id = application_id + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_str) = max { + local_var_req_builder = local_var_req_builder.query(&[("max", &local_var_str.to_string())]); + } + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Given a application ID, it returns application information including creator, approval and clear programs, global and local schemas, and global state. +pub async fn get_application_by_id( + configuration: &configuration::Configuration, + application_id: u64, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/applications/{application_id}", + local_var_configuration.base_path, + application_id = application_id + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Given a asset ID, it returns asset information including creator, name, total supply and special addresses. +pub async fn get_asset_by_id( + configuration: &configuration::Configuration, + asset_id: u64, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/assets/{asset_id}", + local_var_configuration.base_path, + asset_id = asset_id + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +pub async fn get_block( + configuration: &configuration::Configuration, + round: u64, + format: Option<&str>, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/blocks/{round}", + local_var_configuration.base_path, + round = round + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_str) = format { + local_var_req_builder = + local_var_req_builder.query(&[("format", &local_var_str.to_string())]); + } + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +pub async fn get_block_hash( + configuration: &configuration::Configuration, + round: u64, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/blocks/{round}/hash", + local_var_configuration.base_path, + round = round + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +pub async fn get_light_block_header_proof( + configuration: &configuration::Configuration, + round: u64, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/blocks/{round}/lightheader/proof", + local_var_configuration.base_path, + round = round + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +pub async fn get_state_proof( + configuration: &configuration::Configuration, + round: u64, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/stateproofs/{round}", + local_var_configuration.base_path, + round = round + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +pub async fn get_status( + configuration: &configuration::Configuration, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!("{}/v2/status", local_var_configuration.base_path); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +pub async fn get_supply( + configuration: &configuration::Configuration, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!("{}/v2/ledger/supply", local_var_configuration.base_path); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +pub async fn get_transaction_proof( + configuration: &configuration::Configuration, + round: u64, + txid: &str, + hashtype: Option<&str>, + format: Option<&str>, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/blocks/{round}/transactions/{txid}/proof", + local_var_configuration.base_path, + round = round, + txid = crate::apis::urlencode(txid) + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_str) = hashtype { + local_var_req_builder = + local_var_req_builder.query(&[("hashtype", &local_var_str.to_string())]); + } + if let Some(ref local_var_str) = format { + local_var_req_builder = + local_var_req_builder.query(&[("format", &local_var_str.to_string())]); + } + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Special management endpoint to shutdown the node. Optionally provide a timeout parameter to indicate that the node should begin shutting down after a number of seconds. +pub async fn shutdown_node( + configuration: &configuration::Configuration, + timeout: Option, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!("{}/v2/shutdown", local_var_configuration.base_path); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); + + if let Some(ref local_var_str) = timeout { + local_var_req_builder = + local_var_req_builder.query(&[("timeout", &local_var_str.to_string())]); + } + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +pub async fn simulate_transaction( + configuration: &configuration::Configuration, + request: crate::models::SimulateRequest, + format: Option<&str>, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/transactions/simulate", + local_var_configuration.base_path + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); + + if let Some(ref local_var_str) = format { + local_var_req_builder = + local_var_req_builder.query(&[("format", &local_var_str.to_string())]); + } + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + local_var_req_builder = local_var_req_builder.json(&request); + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Given a catchpoint, it starts catching up to this catchpoint +pub async fn start_catchup( + configuration: &configuration::Configuration, + catchpoint: &str, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/catchup/{catchpoint}", + local_var_configuration.base_path, + catchpoint = crate::apis::urlencode(catchpoint) + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Given TEAL source code in plain text, return base64 encoded program bytes and base32 SHA512_256 hash of program bytes (Address style). This endpoint is only enabled when a node's configuration file sets EnableDeveloperAPI to true. +pub async fn teal_compile( + configuration: &configuration::Configuration, + source: &[u8], + sourcemap: Option, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!("{}/v2/teal/compile", local_var_configuration.base_path); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); + + if let Some(ref local_var_str) = sourcemap { + local_var_req_builder = + local_var_req_builder.query(&[("sourcemap", &local_var_str.to_string())]); + } + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + local_var_req_builder = local_var_req_builder.body(source.to_vec()); + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Given the program bytes, return the TEAL source code in plain text. This endpoint is only enabled when a node's configuration file sets EnableDeveloperAPI to true. +pub async fn teal_disassemble( + configuration: &configuration::Configuration, + source: &[u8], +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!("{}/v2/teal/disassemble", local_var_configuration.base_path); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + local_var_req_builder = local_var_req_builder.body(source.to_vec()); + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Executes TEAL program(s) in context and returns debugging information about the execution. This endpoint is only enabled when a node's configuration file sets EnableDeveloperAPI to true. +pub async fn teal_dryrun( + configuration: &configuration::Configuration, + request: Option, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!("{}/v2/teal/dryrun", local_var_configuration.base_path); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + local_var_req_builder = local_var_req_builder.json(&request); + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +pub async fn transaction_params( + configuration: &configuration::Configuration, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/transactions/params", + local_var_configuration.base_path + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Waits for a block to appear after round {round} and returns the node's status at the time. +pub async fn wait_for_block( + configuration: &configuration::Configuration, + round: u64, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/status/wait-for-block-after/{round}", + local_var_configuration.base_path, + round = round + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} diff --git a/algonaut_algod/src/apis/participating_api.rs b/algonaut_algod/src/apis/participating_api.rs new file mode 100644 index 00000000..be79e982 --- /dev/null +++ b/algonaut_algod/src/apis/participating_api.rs @@ -0,0 +1,587 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +use reqwest; + +use super::{configuration, Error}; +use crate::apis::ResponseContent; + +/// struct for typed errors of method [`add_participation_key`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum AddParticipationKeyError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status404(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + Status503(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`append_keys`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum AppendKeysError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status404(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`delete_participation_key_by_id`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum DeleteParticipationKeyByIdError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status404(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_participation_key_by_id`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetParticipationKeyByIdError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status404(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_participation_keys`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetParticipationKeysError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status404(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_pending_transactions`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetPendingTransactionsError { + Status401(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + Status503(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_pending_transactions_by_address`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetPendingTransactionsByAddressError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + Status503(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`pending_transaction_information`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum PendingTransactionInformationError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status404(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`raw_transaction`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum RawTransactionError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + Status503(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +pub async fn add_participation_key( + configuration: &configuration::Configuration, + participationkey: &[u8], +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!("{}/v2/participation", local_var_configuration.base_path); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + local_var_req_builder = local_var_req_builder.body(participationkey.to_vec()); + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Given a participation ID, append state proof keys to a particular set of participation keys +pub async fn append_keys( + configuration: &configuration::Configuration, + participation_id: &str, + keymap: &[u8], +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/participation/{participation_id}", + local_var_configuration.base_path, + participation_id = crate::apis::urlencode(participation_id) + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + local_var_req_builder = local_var_req_builder.body(keymap.to_vec()); + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Delete a given participation key by ID +pub async fn delete_participation_key_by_id( + configuration: &configuration::Configuration, + participation_id: &str, +) -> Result<(), Error> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/participation/{participation_id}", + local_var_configuration.base_path, + participation_id = crate::apis::urlencode(participation_id) + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::DELETE, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + Ok(()) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Given a participation ID, return information about that participation key +pub async fn get_participation_key_by_id( + configuration: &configuration::Configuration, + participation_id: &str, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/participation/{participation_id}", + local_var_configuration.base_path, + participation_id = crate::apis::urlencode(participation_id) + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Return a list of participation keys +pub async fn get_participation_keys( + configuration: &configuration::Configuration, +) -> Result, Error> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!("{}/v2/participation", local_var_configuration.base_path); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Get the list of pending transactions, sorted by priority, in decreasing order, truncated at the end at MAX. If MAX = 0, returns all pending transactions. +pub async fn get_pending_transactions( + configuration: &configuration::Configuration, + max: Option, + format: Option<&str>, +) -> Result< + crate::models::GetPendingTransactionsByAddress200Response, + Error, +> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/transactions/pending", + local_var_configuration.base_path + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_str) = max { + local_var_req_builder = local_var_req_builder.query(&[("max", &local_var_str.to_string())]); + } + if let Some(ref local_var_str) = format { + local_var_req_builder = + local_var_req_builder.query(&[("format", &local_var_str.to_string())]); + } + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Get the list of pending transactions by address, sorted by priority, in decreasing order, truncated at the end at MAX. If MAX = 0, returns all pending transactions. +pub async fn get_pending_transactions_by_address( + configuration: &configuration::Configuration, + address: &str, + max: Option, + format: Option<&str>, +) -> Result< + crate::models::GetPendingTransactionsByAddress200Response, + Error, +> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/accounts/{address}/transactions/pending", + local_var_configuration.base_path, + address = crate::apis::urlencode(address) + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_str) = max { + local_var_req_builder = local_var_req_builder.query(&[("max", &local_var_str.to_string())]); + } + if let Some(ref local_var_str) = format { + local_var_req_builder = + local_var_req_builder.query(&[("format", &local_var_str.to_string())]); + } + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Given a transaction ID of a recently submitted transaction, it returns information about it. There are several cases when this might succeed: - transaction committed (committed round > 0) - transaction still in the pool (committed round = 0, pool error = \"\") - transaction removed from pool due to error (committed round = 0, pool error != \"\") Or the transaction may have happened sufficiently long ago that the node no longer remembers it, and this will return an error. +pub async fn pending_transaction_information( + configuration: &configuration::Configuration, + txid: &str, + format: Option<&str>, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/transactions/pending/{txid}", + local_var_configuration.base_path, + txid = crate::apis::urlencode(txid) + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_str) = format { + local_var_req_builder = + local_var_req_builder.query(&[("format", &local_var_str.to_string())]); + } + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +pub async fn raw_transaction( + configuration: &configuration::Configuration, + rawtxn: &[u8], +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!("{}/v2/transactions", local_var_configuration.base_path); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + local_var_req_builder = local_var_req_builder.body(rawtxn.to_vec()); + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} diff --git a/algonaut_algod/src/apis/private_api.rs b/algonaut_algod/src/apis/private_api.rs new file mode 100644 index 00000000..6503b62c --- /dev/null +++ b/algonaut_algod/src/apis/private_api.rs @@ -0,0 +1,497 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +use reqwest; + +use super::{configuration, Error}; +use crate::apis::ResponseContent; + +/// struct for typed errors of method [`abort_catchup`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum AbortCatchupError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`add_participation_key`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum AddParticipationKeyError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status404(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + Status503(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`append_keys`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum AppendKeysError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status404(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`delete_participation_key_by_id`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum DeleteParticipationKeyByIdError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status404(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_participation_key_by_id`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetParticipationKeyByIdError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status404(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_participation_keys`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetParticipationKeysError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status404(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`shutdown_node`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum ShutdownNodeError { + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`start_catchup`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum StartCatchupError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// Given a catchpoint, it aborts catching up to this catchpoint +pub async fn abort_catchup( + configuration: &configuration::Configuration, + catchpoint: &str, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/catchup/{catchpoint}", + local_var_configuration.base_path, + catchpoint = crate::apis::urlencode(catchpoint) + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::DELETE, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +pub async fn add_participation_key( + configuration: &configuration::Configuration, + participationkey: &[u8], +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!("{}/v2/participation", local_var_configuration.base_path); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + local_var_req_builder = local_var_req_builder.body(participationkey.to_vec()); + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Given a participation ID, append state proof keys to a particular set of participation keys +pub async fn append_keys( + configuration: &configuration::Configuration, + participation_id: &str, + keymap: &[u8], +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/participation/{participation_id}", + local_var_configuration.base_path, + participation_id = crate::apis::urlencode(participation_id) + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + local_var_req_builder = local_var_req_builder.body(keymap.to_vec()); + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Delete a given participation key by ID +pub async fn delete_participation_key_by_id( + configuration: &configuration::Configuration, + participation_id: &str, +) -> Result<(), Error> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/participation/{participation_id}", + local_var_configuration.base_path, + participation_id = crate::apis::urlencode(participation_id) + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::DELETE, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + Ok(()) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Given a participation ID, return information about that participation key +pub async fn get_participation_key_by_id( + configuration: &configuration::Configuration, + participation_id: &str, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/participation/{participation_id}", + local_var_configuration.base_path, + participation_id = crate::apis::urlencode(participation_id) + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Return a list of participation keys +pub async fn get_participation_keys( + configuration: &configuration::Configuration, +) -> Result, Error> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!("{}/v2/participation", local_var_configuration.base_path); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Special management endpoint to shutdown the node. Optionally provide a timeout parameter to indicate that the node should begin shutting down after a number of seconds. +pub async fn shutdown_node( + configuration: &configuration::Configuration, + timeout: Option, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!("{}/v2/shutdown", local_var_configuration.base_path); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); + + if let Some(ref local_var_str) = timeout { + local_var_req_builder = + local_var_req_builder.query(&[("timeout", &local_var_str.to_string())]); + } + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Given a catchpoint, it starts catching up to this catchpoint +pub async fn start_catchup( + configuration: &configuration::Configuration, + catchpoint: &str, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/catchup/{catchpoint}", + local_var_configuration.base_path, + catchpoint = crate::apis::urlencode(catchpoint) + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} diff --git a/algonaut_algod/src/apis/public_api.rs b/algonaut_algod/src/apis/public_api.rs new file mode 100644 index 00000000..aa95ee92 --- /dev/null +++ b/algonaut_algod/src/apis/public_api.rs @@ -0,0 +1,2157 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +use reqwest; + +use super::{configuration, Error}; +use crate::apis::ResponseContent; + +/// struct for typed errors of method [`account_application_information`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum AccountApplicationInformationError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`account_asset_information`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum AccountAssetInformationError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`account_information`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum AccountInformationError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`experimental_check`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum ExperimentalCheckError { + Status404(), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_application_box_by_name`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetApplicationBoxByNameError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status404(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_application_boxes`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetApplicationBoxesError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_application_by_id`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetApplicationByIdError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status404(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_asset_by_id`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetAssetByIdError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status404(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_block`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetBlockError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status404(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_block_hash`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetBlockHashError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status404(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_genesis`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetGenesisError { + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_ledger_state_delta`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetLedgerStateDeltaError { + Status401(crate::models::ErrorResponse), + Status404(crate::models::ErrorResponse), + Status408(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + Status503(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_light_block_header_proof`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetLightBlockHeaderProofError { + Status401(crate::models::ErrorResponse), + Status404(crate::models::ErrorResponse), + Status408(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + Status503(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_pending_transactions`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetPendingTransactionsError { + Status401(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + Status503(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_pending_transactions_by_address`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetPendingTransactionsByAddressError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + Status503(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_ready`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetReadyError { + Status500(), + Status503(), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_state_proof`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetStateProofError { + Status401(crate::models::ErrorResponse), + Status404(crate::models::ErrorResponse), + Status408(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + Status503(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_status`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetStatusError { + Status401(crate::models::ErrorResponse), + Status500(String), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_supply`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetSupplyError { + Status401(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_sync_round`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetSyncRoundError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + Status503(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_transaction_proof`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetTransactionProofError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status404(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`get_version`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum GetVersionError { + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`health_check`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum HealthCheckError { + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`metrics`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum MetricsError { + Status404(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`pending_transaction_information`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum PendingTransactionInformationError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status404(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`raw_transaction`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum RawTransactionError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + Status503(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`set_sync_round`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum SetSyncRoundError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + Status503(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`simulate_transaction`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum SimulateTransactionError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + Status503(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`swagger_json`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum SwaggerJsonError { + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`teal_compile`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum TealCompileError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status404(), + Status500(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`teal_disassemble`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum TealDisassembleError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status404(), + Status500(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`teal_dryrun`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum TealDryrunError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status404(), + Status500(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`transaction_params`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum TransactionParamsError { + Status401(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + Status503(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`unset_sync_round`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum UnsetSyncRoundError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + Status503(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// struct for typed errors of method [`wait_for_block`] +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum WaitForBlockError { + Status400(crate::models::ErrorResponse), + Status401(crate::models::ErrorResponse), + Status500(crate::models::ErrorResponse), + Status503(crate::models::ErrorResponse), + DefaultResponse(), + UnknownValue(serde_json::Value), +} + +/// Given a specific account public key and application ID, this call returns the account's application local state and global state (AppLocalState and AppParams, if either exists). Global state will only be returned if the provided address is the application's creator. +pub async fn account_application_information( + configuration: &configuration::Configuration, + address: &str, + application_id: u64, + format: Option<&str>, +) -> Result< + crate::models::AccountApplicationInformation200Response, + Error, +> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/accounts/{address}/applications/{application_id}", + local_var_configuration.base_path, + address = crate::apis::urlencode(address), + application_id = application_id + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_str) = format { + local_var_req_builder = + local_var_req_builder.query(&[("format", &local_var_str.to_string())]); + } + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Given a specific account public key and asset ID, this call returns the account's asset holding and asset parameters (if either exist). Asset parameters will only be returned if the provided address is the asset's creator. +pub async fn account_asset_information( + configuration: &configuration::Configuration, + address: &str, + asset_id: u64, + format: Option<&str>, +) -> Result> +{ + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/accounts/{address}/assets/{asset_id}", + local_var_configuration.base_path, + address = crate::apis::urlencode(address), + asset_id = asset_id + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_str) = format { + local_var_req_builder = + local_var_req_builder.query(&[("format", &local_var_str.to_string())]); + } + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Given a specific account public key, this call returns the accounts status, balance and spendable amounts +pub async fn account_information( + configuration: &configuration::Configuration, + address: &str, + format: Option<&str>, + exclude: Option<&str>, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/accounts/{address}", + local_var_configuration.base_path, + address = crate::apis::urlencode(address) + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_str) = format { + local_var_req_builder = + local_var_req_builder.query(&[("format", &local_var_str.to_string())]); + } + if let Some(ref local_var_str) = exclude { + local_var_req_builder = + local_var_req_builder.query(&[("exclude", &local_var_str.to_string())]); + } + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +pub async fn experimental_check( + configuration: &configuration::Configuration, +) -> Result<(), Error> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!("{}/v2/experimental", local_var_configuration.base_path); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + Ok(()) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Given an application ID and box name, it returns the box name and value (each base64 encoded). Box names must be in the goal app call arg encoding form 'encoding:value'. For ints, use the form 'int:1234'. For raw bytes, use the form 'b64:A=='. For printable strings, use the form 'str:hello'. For addresses, use the form 'addr:XYZ...'. +pub async fn get_application_box_by_name( + configuration: &configuration::Configuration, + application_id: u64, + name: &str, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/applications/{application_id}/box", + local_var_configuration.base_path, + application_id = application_id + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + local_var_req_builder = local_var_req_builder.query(&[("name", &name.to_string())]); + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Given an application ID, return all Box names. No particular ordering is guaranteed. Request fails when client or server-side configured limits prevent returning all Box names. +pub async fn get_application_boxes( + configuration: &configuration::Configuration, + application_id: u64, + max: Option, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/applications/{application_id}/boxes", + local_var_configuration.base_path, + application_id = application_id + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_str) = max { + local_var_req_builder = local_var_req_builder.query(&[("max", &local_var_str.to_string())]); + } + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Given a application ID, it returns application information including creator, approval and clear programs, global and local schemas, and global state. +pub async fn get_application_by_id( + configuration: &configuration::Configuration, + application_id: u64, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/applications/{application_id}", + local_var_configuration.base_path, + application_id = application_id + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Given a asset ID, it returns asset information including creator, name, total supply and special addresses. +pub async fn get_asset_by_id( + configuration: &configuration::Configuration, + asset_id: u64, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/assets/{asset_id}", + local_var_configuration.base_path, + asset_id = asset_id + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +pub async fn get_block( + configuration: &configuration::Configuration, + round: u64, + format: Option<&str>, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/blocks/{round}", + local_var_configuration.base_path, + round = round + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_str) = format { + local_var_req_builder = + local_var_req_builder.query(&[("format", &local_var_str.to_string())]); + } + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +pub async fn get_block_hash( + configuration: &configuration::Configuration, + round: u64, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/blocks/{round}/hash", + local_var_configuration.base_path, + round = round + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Returns the entire genesis file in json. +pub async fn get_genesis( + configuration: &configuration::Configuration, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!("{}/genesis", local_var_configuration.base_path); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Get ledger deltas for a round. +pub async fn get_ledger_state_delta( + configuration: &configuration::Configuration, + round: u64, + format: Option<&str>, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/deltas/{round}", + local_var_configuration.base_path, + round = round + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_str) = format { + local_var_req_builder = + local_var_req_builder.query(&[("format", &local_var_str.to_string())]); + } + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +pub async fn get_light_block_header_proof( + configuration: &configuration::Configuration, + round: u64, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/blocks/{round}/lightheader/proof", + local_var_configuration.base_path, + round = round + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Get the list of pending transactions, sorted by priority, in decreasing order, truncated at the end at MAX. If MAX = 0, returns all pending transactions. +pub async fn get_pending_transactions( + configuration: &configuration::Configuration, + max: Option, + format: Option<&str>, +) -> Result< + crate::models::GetPendingTransactionsByAddress200Response, + Error, +> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/transactions/pending", + local_var_configuration.base_path + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_str) = max { + local_var_req_builder = local_var_req_builder.query(&[("max", &local_var_str.to_string())]); + } + if let Some(ref local_var_str) = format { + local_var_req_builder = + local_var_req_builder.query(&[("format", &local_var_str.to_string())]); + } + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Get the list of pending transactions by address, sorted by priority, in decreasing order, truncated at the end at MAX. If MAX = 0, returns all pending transactions. +pub async fn get_pending_transactions_by_address( + configuration: &configuration::Configuration, + address: &str, + max: Option, + format: Option<&str>, +) -> Result< + crate::models::GetPendingTransactionsByAddress200Response, + Error, +> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/accounts/{address}/transactions/pending", + local_var_configuration.base_path, + address = crate::apis::urlencode(address) + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_str) = max { + local_var_req_builder = local_var_req_builder.query(&[("max", &local_var_str.to_string())]); + } + if let Some(ref local_var_str) = format { + local_var_req_builder = + local_var_req_builder.query(&[("format", &local_var_str.to_string())]); + } + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +pub async fn get_ready( + configuration: &configuration::Configuration, +) -> Result<(), Error> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!("{}/ready", local_var_configuration.base_path); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + Ok(()) + } else { + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +pub async fn get_state_proof( + configuration: &configuration::Configuration, + round: u64, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/stateproofs/{round}", + local_var_configuration.base_path, + round = round + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +pub async fn get_status( + configuration: &configuration::Configuration, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!("{}/v2/status", local_var_configuration.base_path); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +pub async fn get_supply( + configuration: &configuration::Configuration, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!("{}/v2/ledger/supply", local_var_configuration.base_path); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Gets the minimum sync round for the ledger. +pub async fn get_sync_round( + configuration: &configuration::Configuration, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!("{}/v2/ledger/sync", local_var_configuration.base_path); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +pub async fn get_transaction_proof( + configuration: &configuration::Configuration, + round: u64, + txid: &str, + hashtype: Option<&str>, + format: Option<&str>, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/blocks/{round}/transactions/{txid}/proof", + local_var_configuration.base_path, + round = round, + txid = crate::apis::urlencode(txid) + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_str) = hashtype { + local_var_req_builder = + local_var_req_builder.query(&[("hashtype", &local_var_str.to_string())]); + } + if let Some(ref local_var_str) = format { + local_var_req_builder = + local_var_req_builder.query(&[("format", &local_var_str.to_string())]); + } + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Retrieves the supported API versions, binary build versions, and genesis information. +pub async fn get_version( + configuration: &configuration::Configuration, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!("{}/versions", local_var_configuration.base_path); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +pub async fn health_check( + configuration: &configuration::Configuration, +) -> Result<(), Error> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!("{}/health", local_var_configuration.base_path); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + Ok(()) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +pub async fn metrics( + configuration: &configuration::Configuration, +) -> Result<(), Error> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!("{}/metrics", local_var_configuration.base_path); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + Ok(()) + } else { + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Given a transaction ID of a recently submitted transaction, it returns information about it. There are several cases when this might succeed: - transaction committed (committed round > 0) - transaction still in the pool (committed round = 0, pool error = \"\") - transaction removed from pool due to error (committed round = 0, pool error != \"\") Or the transaction may have happened sufficiently long ago that the node no longer remembers it, and this will return an error. +pub async fn pending_transaction_information( + configuration: &configuration::Configuration, + txid: &str, + format: Option<&str>, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/transactions/pending/{txid}", + local_var_configuration.base_path, + txid = crate::apis::urlencode(txid) + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_str) = format { + local_var_req_builder = + local_var_req_builder.query(&[("format", &local_var_str.to_string())]); + } + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +pub async fn raw_transaction( + configuration: &configuration::Configuration, + rawtxn: &[u8], +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!("{}/v2/transactions", local_var_configuration.base_path); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + // TODO check for a better type that implements Into + local_var_req_builder = local_var_req_builder.body(rawtxn.to_vec()); + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Sets the minimum sync round on the ledger. +pub async fn set_sync_round( + configuration: &configuration::Configuration, + round: u64, +) -> Result<(), Error> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/ledger/sync/{round}", + local_var_configuration.base_path, + round = round + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + Ok(()) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +pub async fn simulate_transaction( + configuration: &configuration::Configuration, + request: crate::models::SimulateRequest, + format: Option<&str>, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/transactions/simulate", + local_var_configuration.base_path + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); + + if let Some(ref local_var_str) = format { + local_var_req_builder = + local_var_req_builder.query(&[("format", &local_var_str.to_string())]); + } + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + local_var_req_builder = local_var_req_builder.json(&request); + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Returns the entire swagger spec in json. +pub async fn swagger_json( + configuration: &configuration::Configuration, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!("{}/swagger.json", local_var_configuration.base_path); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Given TEAL source code in plain text, return base64 encoded program bytes and base32 SHA512_256 hash of program bytes (Address style). This endpoint is only enabled when a node's configuration file sets EnableDeveloperAPI to true. +pub async fn teal_compile( + configuration: &configuration::Configuration, + source: &[u8], + sourcemap: Option, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!("{}/v2/teal/compile", local_var_configuration.base_path); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); + + if let Some(ref local_var_str) = sourcemap { + local_var_req_builder = + local_var_req_builder.query(&[("sourcemap", &local_var_str.to_string())]); + } + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + local_var_req_builder = local_var_req_builder.body(source.to_vec()); + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Given the program bytes, return the TEAL source code in plain text. This endpoint is only enabled when a node's configuration file sets EnableDeveloperAPI to true. +pub async fn teal_disassemble( + configuration: &configuration::Configuration, + source: &[u8], +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!("{}/v2/teal/disassemble", local_var_configuration.base_path); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + local_var_req_builder = local_var_req_builder.body(source.to_vec()); + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Executes TEAL program(s) in context and returns debugging information about the execution. This endpoint is only enabled when a node's configuration file sets EnableDeveloperAPI to true. +pub async fn teal_dryrun( + configuration: &configuration::Configuration, + request: Option, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!("{}/v2/teal/dryrun", local_var_configuration.base_path); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + local_var_req_builder = local_var_req_builder.json(&request); + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +pub async fn transaction_params( + configuration: &configuration::Configuration, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/transactions/params", + local_var_configuration.base_path + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Unset the ledger sync round. +pub async fn unset_sync_round( + configuration: &configuration::Configuration, +) -> Result<(), Error> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!("{}/v2/ledger/sync", local_var_configuration.base_path); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::DELETE, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + Ok(()) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} + +/// Waits for a block to appear after round {round} and returns the node's status at the time. +pub async fn wait_for_block( + configuration: &configuration::Configuration, + round: u64, +) -> Result> { + let local_var_configuration = configuration; + + let local_var_client = &local_var_configuration.client; + + let local_var_uri_str = format!( + "{}/v2/status/wait-for-block-after/{round}", + local_var_configuration.base_path, + round = round + ); + let mut local_var_req_builder = + local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str()); + + if let Some(ref local_var_user_agent) = local_var_configuration.user_agent { + local_var_req_builder = + local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); + } + if let Some(ref local_var_apikey) = local_var_configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, + }; + local_var_req_builder = local_var_req_builder.header("X-Algo-API-Token", local_var_value); + }; + + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; + + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; + + if !local_var_status.is_client_error() && !local_var_status.is_server_error() { + serde_json::from_str(&local_var_content).map_err(Error::from) + } else { + let local_var_entity: Option = + serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { + status: local_var_status, + content: local_var_content, + entity: local_var_entity, + }; + Err(Error::ResponseError(local_var_error)) + } +} diff --git a/algonaut_algod/src/lib.rs b/algonaut_algod/src/lib.rs new file mode 100644 index 00000000..fc22e4e4 --- /dev/null +++ b/algonaut_algod/src/lib.rs @@ -0,0 +1,10 @@ +#[macro_use] +extern crate serde_derive; + +extern crate reqwest; +extern crate serde; +extern crate serde_json; +extern crate url; + +pub mod apis; +pub mod models; diff --git a/algonaut_algod/src/models/abort_catchup_200_response.rs b/algonaut_algod/src/models/abort_catchup_200_response.rs new file mode 100644 index 00000000..cc60512b --- /dev/null +++ b/algonaut_algod/src/models/abort_catchup_200_response.rs @@ -0,0 +1,25 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +/// AbortCatchup200Response : An catchpoint abort response. + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct AbortCatchup200Response { + /// Catchup abort response string + #[serde(rename = "catchup-message")] + pub catchup_message: String, +} + +impl AbortCatchup200Response { + /// An catchpoint abort response. + pub fn new(catchup_message: String) -> AbortCatchup200Response { + AbortCatchup200Response { catchup_message } + } +} diff --git a/algonaut_algod/src/models/account.rs b/algonaut_algod/src/models/account.rs new file mode 100644 index 00000000..a3c19feb --- /dev/null +++ b/algonaut_algod/src/models/account.rs @@ -0,0 +1,151 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +/// Account : Account information at a given round. Definition: data/basics/userBalance.go : AccountData + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct Account { + /// the account public key + #[serde(rename = "address")] + pub address: String, + /// \\[algo\\] total number of MicroAlgos in the account + #[serde(rename = "amount")] + pub amount: u64, + /// specifies the amount of MicroAlgos in the account, without the pending rewards. + #[serde(rename = "amount-without-pending-rewards")] + pub amount_without_pending_rewards: u64, + /// \\[appl\\] applications local data stored in this account. Note the raw object uses `map[int] -> AppLocalState` for this type. + #[serde(rename = "apps-local-state", skip_serializing_if = "Option::is_none")] + pub apps_local_state: Option>, + /// \\[teap\\] the sum of all extra application program pages for this account. + #[serde( + rename = "apps-total-extra-pages", + skip_serializing_if = "Option::is_none" + )] + pub apps_total_extra_pages: Option, + #[serde(rename = "apps-total-schema", skip_serializing_if = "Option::is_none")] + pub apps_total_schema: Option>, + /// \\[asset\\] assets held by this account. Note the raw object uses `map[int] -> AssetHolding` for this type. + #[serde(rename = "assets", skip_serializing_if = "Option::is_none")] + pub assets: Option>, + /// \\[spend\\] the address against which signing should be checked. If empty, the address of the current account is used. This field can be updated in any transaction by setting the RekeyTo field. + #[serde(rename = "auth-addr", skip_serializing_if = "Option::is_none")] + pub auth_addr: Option, + /// \\[appp\\] parameters of applications created by this account including app global data. Note: the raw account uses `map[int] -> AppParams` for this type. + #[serde(rename = "created-apps", skip_serializing_if = "Option::is_none")] + pub created_apps: Option>, + /// \\[apar\\] parameters of assets created by this account. Note: the raw account uses `map[int] -> Asset` for this type. + #[serde(rename = "created-assets", skip_serializing_if = "Option::is_none")] + pub created_assets: Option>, + /// MicroAlgo balance required by the account. The requirement grows based on asset and application usage. + #[serde(rename = "min-balance")] + pub min_balance: u64, + #[serde(rename = "participation", skip_serializing_if = "Option::is_none")] + pub participation: Option>, + /// amount of MicroAlgos of pending rewards in this account. + #[serde(rename = "pending-rewards")] + pub pending_rewards: u64, + /// \\[ebase\\] used as part of the rewards computation. Only applicable to accounts which are participating. + #[serde(rename = "reward-base", skip_serializing_if = "Option::is_none")] + pub reward_base: Option, + /// \\[ern\\] total rewards of MicroAlgos the account has received, including pending rewards. + #[serde(rename = "rewards")] + pub rewards: u64, + /// The round for which this information is relevant. + #[serde(rename = "round")] + pub round: u64, + /// Indicates what type of signature is used by this account, must be one of: * sig * msig * lsig + #[serde(rename = "sig-type", skip_serializing_if = "Option::is_none")] + pub sig_type: Option, + /// \\[onl\\] delegation status of the account's MicroAlgos * Offline - indicates that the associated account is delegated. * Online - indicates that the associated account used as part of the delegation pool. * NotParticipating - indicates that the associated account is neither a delegator nor a delegate. + #[serde(rename = "status")] + pub status: String, + /// The count of all applications that have been opted in, equivalent to the count of application local data (AppLocalState objects) stored in this account. + #[serde(rename = "total-apps-opted-in")] + pub total_apps_opted_in: u64, + /// The count of all assets that have been opted in, equivalent to the count of AssetHolding objects held by this account. + #[serde(rename = "total-assets-opted-in")] + pub total_assets_opted_in: u64, + /// \\[tbxb\\] The total number of bytes used by this account's app's box keys and values. + #[serde(rename = "total-box-bytes", skip_serializing_if = "Option::is_none")] + pub total_box_bytes: Option, + /// \\[tbx\\] The number of existing boxes created by this account's app. + #[serde(rename = "total-boxes", skip_serializing_if = "Option::is_none")] + pub total_boxes: Option, + /// The count of all apps (AppParams objects) created by this account. + #[serde(rename = "total-created-apps")] + pub total_created_apps: u64, + /// The count of all assets (AssetParams objects) created by this account. + #[serde(rename = "total-created-assets")] + pub total_created_assets: u64, +} + +#[allow(clippy::too_many_arguments)] +impl Account { + /// Account information at a given round. Definition: data/basics/userBalance.go : AccountData + pub fn new( + address: String, + amount: u64, + amount_without_pending_rewards: u64, + min_balance: u64, + pending_rewards: u64, + rewards: u64, + round: u64, + status: String, + total_apps_opted_in: u64, + total_assets_opted_in: u64, + total_created_apps: u64, + total_created_assets: u64, + ) -> Account { + Account { + address, + amount, + amount_without_pending_rewards, + apps_local_state: None, + apps_total_extra_pages: None, + apps_total_schema: None, + assets: None, + auth_addr: None, + created_apps: None, + created_assets: None, + min_balance, + participation: None, + pending_rewards, + reward_base: None, + rewards, + round, + sig_type: None, + status, + total_apps_opted_in, + total_assets_opted_in, + total_box_bytes: None, + total_boxes: None, + total_created_apps, + total_created_assets, + } + } +} + +/// Indicates what type of signature is used by this account, must be one of: * sig * msig * lsig +#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] +pub enum SigType { + #[serde(rename = "sig")] + Sig, + #[serde(rename = "msig")] + Msig, + #[serde(rename = "lsig")] + Lsig, +} + +impl Default for SigType { + fn default() -> SigType { + Self::Sig + } +} diff --git a/algonaut_algod/src/models/account_application_information_200_response.rs b/algonaut_algod/src/models/account_application_information_200_response.rs new file mode 100644 index 00000000..46cb04b2 --- /dev/null +++ b/algonaut_algod/src/models/account_application_information_200_response.rs @@ -0,0 +1,30 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct AccountApplicationInformation200Response { + #[serde(rename = "app-local-state", skip_serializing_if = "Option::is_none")] + pub app_local_state: Option>, + #[serde(rename = "created-app", skip_serializing_if = "Option::is_none")] + pub created_app: Option>, + /// The round for which this information is relevant. + #[serde(rename = "round")] + pub round: u64, +} + +impl AccountApplicationInformation200Response { + pub fn new(round: u64) -> AccountApplicationInformation200Response { + AccountApplicationInformation200Response { + app_local_state: None, + created_app: None, + round, + } + } +} diff --git a/algonaut_algod/src/models/account_asset_information_200_response.rs b/algonaut_algod/src/models/account_asset_information_200_response.rs new file mode 100644 index 00000000..eed4fcb2 --- /dev/null +++ b/algonaut_algod/src/models/account_asset_information_200_response.rs @@ -0,0 +1,30 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct AccountAssetInformation200Response { + #[serde(rename = "asset-holding", skip_serializing_if = "Option::is_none")] + pub asset_holding: Option>, + #[serde(rename = "created-asset", skip_serializing_if = "Option::is_none")] + pub created_asset: Option>, + /// The round for which this information is relevant. + #[serde(rename = "round")] + pub round: u64, +} + +impl AccountAssetInformation200Response { + pub fn new(round: u64) -> AccountAssetInformation200Response { + AccountAssetInformation200Response { + asset_holding: None, + created_asset: None, + round, + } + } +} diff --git a/algonaut_algod/src/models/account_participation.rs b/algonaut_algod/src/models/account_participation.rs new file mode 100644 index 00000000..7ec0e8ce --- /dev/null +++ b/algonaut_algod/src/models/account_participation.rs @@ -0,0 +1,55 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +use algonaut_encoding::Bytes; + +/// AccountParticipation : AccountParticipation describes the parameters used by this account in consensus protocol. + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct AccountParticipation { + /// \\[sel\\] Selection public key (if any) currently registered for this round. + #[serde(rename = "selection-participation-key")] + pub selection_participation_key: Bytes, + /// \\[stprf\\] Root of the state proof key (if any) + #[serde(rename = "state-proof-key", skip_serializing_if = "Option::is_none")] + pub state_proof_key: Option, + /// \\[voteFst\\] First round for which this participation is valid. + #[serde(rename = "vote-first-valid")] + pub vote_first_valid: u64, + /// \\[voteKD\\] Number of subkeys in each batch of participation keys. + #[serde(rename = "vote-key-dilution")] + pub vote_key_dilution: u64, + /// \\[voteLst\\] Last round for which this participation is valid. + #[serde(rename = "vote-last-valid")] + pub vote_last_valid: u64, + /// \\[vote\\] root participation public key (if any) currently registered for this round. + #[serde(rename = "vote-participation-key")] + pub vote_participation_key: Bytes, +} + +impl AccountParticipation { + /// AccountParticipation describes the parameters used by this account in consensus protocol. + pub fn new( + selection_participation_key: Bytes, + vote_first_valid: u64, + vote_key_dilution: u64, + vote_last_valid: u64, + vote_participation_key: Bytes, + ) -> AccountParticipation { + AccountParticipation { + selection_participation_key, + state_proof_key: None, + vote_first_valid, + vote_key_dilution, + vote_last_valid, + vote_participation_key, + } + } +} diff --git a/algonaut_algod/src/models/account_state_delta.rs b/algonaut_algod/src/models/account_state_delta.rs new file mode 100644 index 00000000..d09f1fde --- /dev/null +++ b/algonaut_algod/src/models/account_state_delta.rs @@ -0,0 +1,27 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +/// AccountStateDelta : Application state delta. + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct AccountStateDelta { + #[serde(rename = "address")] + pub address: String, + /// Application state delta. + #[serde(rename = "delta")] + pub delta: Vec, +} + +impl AccountStateDelta { + /// Application state delta. + pub fn new(address: String, delta: Vec) -> AccountStateDelta { + AccountStateDelta { address, delta } + } +} diff --git a/algonaut_algod/src/models/add_participation_key_200_response.rs b/algonaut_algod/src/models/add_participation_key_200_response.rs new file mode 100644 index 00000000..f3aecb88 --- /dev/null +++ b/algonaut_algod/src/models/add_participation_key_200_response.rs @@ -0,0 +1,22 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct AddParticipationKey200Response { + /// encoding of the participation ID. + #[serde(rename = "partId")] + pub part_id: String, +} + +impl AddParticipationKey200Response { + pub fn new(part_id: String) -> AddParticipationKey200Response { + AddParticipationKey200Response { part_id } + } +} diff --git a/algonaut_algod/src/models/application.rs b/algonaut_algod/src/models/application.rs new file mode 100644 index 00000000..ea7afd3c --- /dev/null +++ b/algonaut_algod/src/models/application.rs @@ -0,0 +1,30 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +/// Application : Application index and its parameters + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct Application { + /// \\[appidx\\] application index. + #[serde(rename = "id")] + pub id: u64, + #[serde(rename = "params")] + pub params: Box, +} + +impl Application { + /// Application index and its parameters + pub fn new(id: u64, params: crate::models::ApplicationParams) -> Application { + Application { + id, + params: Box::new(params), + } + } +} diff --git a/algonaut_algod/src/models/application_local_state.rs b/algonaut_algod/src/models/application_local_state.rs new file mode 100644 index 00000000..c0673d0a --- /dev/null +++ b/algonaut_algod/src/models/application_local_state.rs @@ -0,0 +1,34 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +/// ApplicationLocalState : Stores local state associated with an application. + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct ApplicationLocalState { + /// The application which this local state is for. + #[serde(rename = "id")] + pub id: u64, + /// Represents a key-value store for use in an application. + #[serde(rename = "key-value", skip_serializing_if = "Option::is_none")] + pub key_value: Option>, + #[serde(rename = "schema")] + pub schema: Box, +} + +impl ApplicationLocalState { + /// Stores local state associated with an application. + pub fn new(id: u64, schema: crate::models::ApplicationStateSchema) -> ApplicationLocalState { + ApplicationLocalState { + id, + key_value: None, + schema: Box::new(schema), + } + } +} diff --git a/algonaut_algod/src/models/application_params.rs b/algonaut_algod/src/models/application_params.rs new file mode 100644 index 00000000..af61b69c --- /dev/null +++ b/algonaut_algod/src/models/application_params.rs @@ -0,0 +1,61 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +use algonaut_encoding::Bytes; + +/// ApplicationParams : Stores the global information associated with an application. + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct ApplicationParams { + /// \\[approv\\] approval program. + #[serde(rename = "approval-program")] + pub approval_program: Bytes, + /// \\[clearp\\] approval program. + #[serde(rename = "clear-state-program")] + pub clear_state_program: Bytes, + /// The address that created this application. This is the address where the parameters and global state for this application can be found. + #[serde(rename = "creator")] + pub creator: String, + /// \\[epp\\] the amount of extra program pages available to this app. + #[serde( + rename = "extra-program-pages", + skip_serializing_if = "Option::is_none" + )] + pub extra_program_pages: Option, + /// Represents a key-value store for use in an application. + #[serde(rename = "global-state", skip_serializing_if = "Option::is_none")] + pub global_state: Option>, + #[serde( + rename = "global-state-schema", + skip_serializing_if = "Option::is_none" + )] + pub global_state_schema: Option>, + #[serde(rename = "local-state-schema", skip_serializing_if = "Option::is_none")] + pub local_state_schema: Option>, +} + +impl ApplicationParams { + /// Stores the global information associated with an application. + pub fn new( + approval_program: Bytes, + clear_state_program: Bytes, + creator: String, + ) -> ApplicationParams { + ApplicationParams { + approval_program, + clear_state_program, + creator, + extra_program_pages: None, + global_state: None, + global_state_schema: None, + local_state_schema: None, + } + } +} diff --git a/algonaut_algod/src/models/application_state_schema.rs b/algonaut_algod/src/models/application_state_schema.rs new file mode 100644 index 00000000..ddbd3c8c --- /dev/null +++ b/algonaut_algod/src/models/application_state_schema.rs @@ -0,0 +1,31 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +/// ApplicationStateSchema : Specifies maximums on the number of each type that may be stored. + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct ApplicationStateSchema { + /// \\[nbs\\] num of byte slices. + #[serde(rename = "num-byte-slice")] + pub num_byte_slice: u64, + /// \\[nui\\] num of uints. + #[serde(rename = "num-uint")] + pub num_uint: u64, +} + +impl ApplicationStateSchema { + /// Specifies maximums on the number of each type that may be stored. + pub fn new(num_byte_slice: u64, num_uint: u64) -> ApplicationStateSchema { + ApplicationStateSchema { + num_byte_slice, + num_uint, + } + } +} diff --git a/algonaut_algod/src/models/asset.rs b/algonaut_algod/src/models/asset.rs new file mode 100644 index 00000000..0cea33c4 --- /dev/null +++ b/algonaut_algod/src/models/asset.rs @@ -0,0 +1,30 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +/// Asset : Specifies both the unique identifier and the parameters for an asset + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct Asset { + /// unique asset identifier + #[serde(rename = "index")] + pub index: u64, + #[serde(rename = "params")] + pub params: Box, +} + +impl Asset { + /// Specifies both the unique identifier and the parameters for an asset + pub fn new(index: u64, params: crate::models::AssetParams) -> Asset { + Asset { + index, + params: Box::new(params), + } + } +} diff --git a/algonaut_algod/src/models/asset_holding.rs b/algonaut_algod/src/models/asset_holding.rs new file mode 100644 index 00000000..c8b672a1 --- /dev/null +++ b/algonaut_algod/src/models/asset_holding.rs @@ -0,0 +1,35 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +/// AssetHolding : Describes an asset held by an account. Definition: data/basics/userBalance.go : AssetHolding + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct AssetHolding { + /// \\[a\\] number of units held. + #[serde(rename = "amount")] + pub amount: u64, + /// Asset ID of the holding. + #[serde(rename = "asset-id")] + pub asset_id: u64, + /// \\[f\\] whether or not the holding is frozen. + #[serde(rename = "is-frozen")] + pub is_frozen: bool, +} + +impl AssetHolding { + /// Describes an asset held by an account. Definition: data/basics/userBalance.go : AssetHolding + pub fn new(amount: u64, asset_id: u64, is_frozen: bool) -> AssetHolding { + AssetHolding { + amount, + asset_id, + is_frozen, + } + } +} diff --git a/algonaut_algod/src/models/asset_params.rs b/algonaut_algod/src/models/asset_params.rs new file mode 100644 index 00000000..ec56532d --- /dev/null +++ b/algonaut_algod/src/models/asset_params.rs @@ -0,0 +1,90 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +use algonaut_crypto::{deserialize_opt_hash, HashDigest}; +use algonaut_encoding::Bytes; + +/// AssetParams : AssetParams specifies the parameters for an asset. \\[apar\\] when part of an AssetConfig transaction. Definition: data/transactions/asset.go : AssetParams + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct AssetParams { + /// \\[c\\] Address of account used to clawback holdings of this asset. If empty, clawback is not permitted. + #[serde(rename = "clawback", skip_serializing_if = "Option::is_none")] + pub clawback: Option, + /// The address that created this asset. This is the address where the parameters for this asset can be found, and also the address where unwanted asset units can be sent in the worst case. + #[serde(rename = "creator")] + pub creator: String, + /// \\[dc\\] The number of digits to use after the decimal point when displaying this asset. If 0, the asset is not divisible. If 1, the base unit of the asset is in tenths. If 2, the base unit of the asset is in hundredths, and so on. This value must be between 0 and 19 (inclusive). + #[serde(rename = "decimals")] + pub decimals: u64, + /// \\[df\\] Whether holdings of this asset are frozen by default. + #[serde(rename = "default-frozen", skip_serializing_if = "Option::is_none")] + pub default_frozen: Option, + /// \\[f\\] Address of account used to freeze holdings of this asset. If empty, freezing is not permitted. + #[serde(rename = "freeze", skip_serializing_if = "Option::is_none")] + pub freeze: Option, + /// \\[m\\] Address of account used to manage the keys of this asset and to destroy it. + #[serde(rename = "manager", skip_serializing_if = "Option::is_none")] + pub manager: Option, + /// \\[am\\] A commitment to some unspecified asset metadata. The format of this metadata is up to the application. + #[serde( + rename = "metadata-hash", + skip_serializing_if = "Option::is_none", + deserialize_with = "deserialize_opt_hash" + )] + pub metadata_hash: Option, + /// \\[an\\] Name of this asset, as supplied by the creator. Included only when the asset name is composed of printable utf-8 characters. + #[serde(rename = "name", skip_serializing_if = "Option::is_none")] + pub name: Option, + /// Base64 encoded name of this asset, as supplied by the creator. + #[serde(rename = "name-b64", skip_serializing_if = "Option::is_none")] + pub name_b64: Option, + /// \\[r\\] Address of account holding reserve (non-minted) units of this asset. + #[serde(rename = "reserve", skip_serializing_if = "Option::is_none")] + pub reserve: Option, + /// \\[t\\] The total number of units of this asset. + #[serde(rename = "total")] + pub total: u64, + /// \\[un\\] Name of a unit of this asset, as supplied by the creator. Included only when the name of a unit of this asset is composed of printable utf-8 characters. + #[serde(rename = "unit-name", skip_serializing_if = "Option::is_none")] + pub unit_name: Option, + /// Base64 encoded name of a unit of this asset, as supplied by the creator. + #[serde(rename = "unit-name-b64", skip_serializing_if = "Option::is_none")] + pub unit_name_b64: Option, + /// \\[au\\] URL where more information about the asset can be retrieved. Included only when the URL is composed of printable utf-8 characters. + #[serde(rename = "url", skip_serializing_if = "Option::is_none")] + pub url: Option, + /// Base64 encoded URL where more information about the asset can be retrieved. + #[serde(rename = "url-b64", skip_serializing_if = "Option::is_none")] + pub url_b64: Option, +} + +impl AssetParams { + /// AssetParams specifies the parameters for an asset. \\[apar\\] when part of an AssetConfig transaction. Definition: data/transactions/asset.go : AssetParams + pub fn new(creator: String, decimals: u64, total: u64) -> AssetParams { + AssetParams { + clawback: None, + creator, + decimals, + default_frozen: None, + freeze: None, + manager: None, + metadata_hash: None, + name: None, + name_b64: None, + reserve: None, + total, + unit_name: None, + unit_name_b64: None, + url: None, + url_b64: None, + } + } +} diff --git a/algonaut_algod/src/models/box_descriptor.rs b/algonaut_algod/src/models/box_descriptor.rs new file mode 100644 index 00000000..21a98c3e --- /dev/null +++ b/algonaut_algod/src/models/box_descriptor.rs @@ -0,0 +1,27 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +use algonaut_encoding::Bytes; + +/// BoxDescriptor : Box descriptor describes a Box. + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct BoxDescriptor { + /// Base64 encoded box name + #[serde(rename = "name")] + pub name: Bytes, +} + +impl BoxDescriptor { + /// Box descriptor describes a Box. + pub fn new(name: Bytes) -> BoxDescriptor { + BoxDescriptor { name } + } +} diff --git a/algonaut_algod/src/models/build_version.rs b/algonaut_algod/src/models/build_version.rs new file mode 100644 index 00000000..21232f59 --- /dev/null +++ b/algonaut_algod/src/models/build_version.rs @@ -0,0 +1,45 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct BuildVersion { + #[serde(rename = "branch")] + pub branch: String, + #[serde(rename = "build_number")] + pub build_number: u64, + #[serde(rename = "channel")] + pub channel: String, + #[serde(rename = "commit_hash")] + pub commit_hash: String, + #[serde(rename = "major")] + pub major: u64, + #[serde(rename = "minor")] + pub minor: u64, +} + +impl BuildVersion { + pub fn new( + branch: String, + build_number: u64, + channel: String, + commit_hash: String, + major: u64, + minor: u64, + ) -> BuildVersion { + BuildVersion { + branch, + build_number, + channel, + commit_hash, + major, + minor, + } + } +} diff --git a/algonaut_algod/src/models/dryrun_request.rs b/algonaut_algod/src/models/dryrun_request.rs new file mode 100644 index 00000000..80105833 --- /dev/null +++ b/algonaut_algod/src/models/dryrun_request.rs @@ -0,0 +1,57 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +use algonaut_model::transaction::ApiSignedTransaction; + +/// DryrunRequest : Request data type for dryrun endpoint. Given the Transactions and simulated ledger state upload, run TEAL scripts and return debugging information. + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct DryrunRequest { + #[serde(rename = "accounts")] + pub accounts: Vec, + #[serde(rename = "apps")] + pub apps: Vec, + /// LatestTimestamp is available to some TEAL scripts. Defaults to the latest confirmed timestamp this algod is attached to. + #[serde(rename = "latest-timestamp")] + pub latest_timestamp: u64, + /// ProtocolVersion specifies a specific version string to operate under, otherwise whatever the current protocol of the network this algod is running in. + #[serde(rename = "protocol-version")] + pub protocol_version: String, + /// Round is available to some TEAL scripts. Defaults to the current round on the network this algod is attached to. + #[serde(rename = "round")] + pub round: u64, + #[serde(rename = "sources")] + pub sources: Vec, + #[serde(rename = "txns")] + pub txns: Vec, +} + +impl DryrunRequest { + /// Request data type for dryrun endpoint. Given the Transactions and simulated ledger state upload, run TEAL scripts and return debugging information. + pub fn new( + accounts: Vec, + apps: Vec, + latest_timestamp: u64, + protocol_version: String, + round: u64, + sources: Vec, + txns: Vec, + ) -> DryrunRequest { + DryrunRequest { + accounts, + apps, + latest_timestamp, + protocol_version, + round, + sources, + txns, + } + } +} diff --git a/algonaut_algod/src/models/dryrun_source.rs b/algonaut_algod/src/models/dryrun_source.rs new file mode 100644 index 00000000..a08083e1 --- /dev/null +++ b/algonaut_algod/src/models/dryrun_source.rs @@ -0,0 +1,39 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +use algonaut_encoding::Bytes; + +/// DryrunSource : DryrunSource is TEAL source text that gets uploaded, compiled, and inserted into transactions or application state. + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct DryrunSource { + #[serde(rename = "app-index")] + pub app_index: u64, + /// FieldName is what kind of sources this is. If lsig then it goes into the transactions[this.TxnIndex].LogicSig. If approv or clearp it goes into the Approval Program or Clear State Program of application[this.AppIndex]. + #[serde(rename = "field-name")] + pub field_name: String, + /// TEAL program binary + #[serde(rename = "source")] + pub source: Bytes, + #[serde(rename = "txn-index")] + pub txn_index: u64, +} + +impl DryrunSource { + /// DryrunSource is TEAL source text that gets uploaded, compiled, and inserted into transactions or application state. + pub fn new(app_index: u64, field_name: String, source: Bytes, txn_index: u64) -> DryrunSource { + DryrunSource { + app_index, + field_name, + source, + txn_index, + } + } +} diff --git a/algonaut_algod/src/models/dryrun_state.rs b/algonaut_algod/src/models/dryrun_state.rs new file mode 100644 index 00000000..919803aa --- /dev/null +++ b/algonaut_algod/src/models/dryrun_state.rs @@ -0,0 +1,41 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +/// DryrunState : Stores the TEAL eval step data + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct DryrunState { + /// Evaluation error if any + #[serde(rename = "error", skip_serializing_if = "Option::is_none")] + pub error: Option, + /// Line number + #[serde(rename = "line")] + pub line: u64, + /// Program counter + #[serde(rename = "pc")] + pub pc: u64, + #[serde(rename = "scratch", skip_serializing_if = "Option::is_none")] + pub scratch: Option>, + #[serde(rename = "stack")] + pub stack: Vec, +} + +impl DryrunState { + /// Stores the TEAL eval step data + pub fn new(line: u64, pc: u64, stack: Vec) -> DryrunState { + DryrunState { + error: None, + line, + pc, + scratch: None, + stack, + } + } +} diff --git a/algonaut_algod/src/models/dryrun_txn_result.rs b/algonaut_algod/src/models/dryrun_txn_result.rs new file mode 100644 index 00000000..9d3a033b --- /dev/null +++ b/algonaut_algod/src/models/dryrun_txn_result.rs @@ -0,0 +1,66 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +use algonaut_encoding::Bytes; + +/// DryrunTxnResult : DryrunTxnResult contains any LogicSig or ApplicationCall program debug information and state updates from a dryrun. + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct DryrunTxnResult { + #[serde(rename = "app-call-messages", skip_serializing_if = "Option::is_none")] + pub app_call_messages: Option>, + #[serde(rename = "app-call-trace", skip_serializing_if = "Option::is_none")] + pub app_call_trace: Option>, + /// Budget added during execution of app call transaction. + #[serde(rename = "budget-added", skip_serializing_if = "Option::is_none")] + pub budget_added: Option, + /// Budget consumed during execution of app call transaction. + #[serde(rename = "budget-consumed", skip_serializing_if = "Option::is_none")] + pub budget_consumed: Option, + /// Disassembled program line by line. + #[serde(rename = "disassembly")] + pub disassembly: Vec, + /// Application state delta. + #[serde(rename = "global-delta", skip_serializing_if = "Option::is_none")] + pub global_delta: Option>, + #[serde(rename = "local-deltas", skip_serializing_if = "Option::is_none")] + pub local_deltas: Option>, + /// Disassembled lsig program line by line. + #[serde( + rename = "logic-sig-disassembly", + skip_serializing_if = "Option::is_none" + )] + pub logic_sig_disassembly: Option>, + #[serde(rename = "logic-sig-messages", skip_serializing_if = "Option::is_none")] + pub logic_sig_messages: Option>, + #[serde(rename = "logic-sig-trace", skip_serializing_if = "Option::is_none")] + pub logic_sig_trace: Option>, + #[serde(rename = "logs", skip_serializing_if = "Option::is_none")] + pub logs: Option>, +} + +impl DryrunTxnResult { + /// DryrunTxnResult contains any LogicSig or ApplicationCall program debug information and state updates from a dryrun. + pub fn new(disassembly: Vec) -> DryrunTxnResult { + DryrunTxnResult { + app_call_messages: None, + app_call_trace: None, + budget_added: None, + budget_consumed: None, + disassembly, + global_delta: None, + local_deltas: None, + logic_sig_disassembly: None, + logic_sig_messages: None, + logic_sig_trace: None, + logs: None, + } + } +} diff --git a/algonaut_algod/src/models/error_response.rs b/algonaut_algod/src/models/error_response.rs new file mode 100644 index 00000000..d90fa56f --- /dev/null +++ b/algonaut_algod/src/models/error_response.rs @@ -0,0 +1,29 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +/// ErrorResponse : An error response with optional data field. + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct ErrorResponse { + #[serde(rename = "data", skip_serializing_if = "Option::is_none")] + pub data: Option, + #[serde(rename = "message")] + pub message: String, +} + +impl ErrorResponse { + /// An error response with optional data field. + pub fn new(message: String) -> ErrorResponse { + ErrorResponse { + data: None, + message, + } + } +} diff --git a/algonaut_algod/src/models/eval_delta.rs b/algonaut_algod/src/models/eval_delta.rs new file mode 100644 index 00000000..4844991d --- /dev/null +++ b/algonaut_algod/src/models/eval_delta.rs @@ -0,0 +1,35 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +/// EvalDelta : Represents a TEAL value delta. + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct EvalDelta { + /// \\[at\\] delta action. + #[serde(rename = "action")] + pub action: u64, + /// \\[bs\\] bytes value. + #[serde(rename = "bytes", skip_serializing_if = "Option::is_none")] + pub bytes: Option, + /// \\[ui\\] uint value. + #[serde(rename = "uint", skip_serializing_if = "Option::is_none")] + pub uint: Option, +} + +impl EvalDelta { + /// Represents a TEAL value delta. + pub fn new(action: u64) -> EvalDelta { + EvalDelta { + action, + bytes: None, + uint: None, + } + } +} diff --git a/algonaut_algod/src/models/eval_delta_key_value.rs b/algonaut_algod/src/models/eval_delta_key_value.rs new file mode 100644 index 00000000..0c5c5fb3 --- /dev/null +++ b/algonaut_algod/src/models/eval_delta_key_value.rs @@ -0,0 +1,29 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +/// EvalDeltaKeyValue : Key-value pairs for StateDelta. + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct EvalDeltaKeyValue { + #[serde(rename = "key")] + pub key: String, + #[serde(rename = "value")] + pub value: Box, +} + +impl EvalDeltaKeyValue { + /// Key-value pairs for StateDelta. + pub fn new(key: String, value: crate::models::EvalDelta) -> EvalDeltaKeyValue { + EvalDeltaKeyValue { + key, + value: Box::new(value), + } + } +} diff --git a/algonaut_algod/src/models/get_application_boxes_200_response.rs b/algonaut_algod/src/models/get_application_boxes_200_response.rs new file mode 100644 index 00000000..ac5750fa --- /dev/null +++ b/algonaut_algod/src/models/get_application_boxes_200_response.rs @@ -0,0 +1,21 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct GetApplicationBoxes200Response { + #[serde(rename = "boxes")] + pub boxes: Vec, +} + +impl GetApplicationBoxes200Response { + pub fn new(boxes: Vec) -> GetApplicationBoxes200Response { + GetApplicationBoxes200Response { boxes } + } +} diff --git a/algonaut_algod/src/models/get_block_200_response.rs b/algonaut_algod/src/models/get_block_200_response.rs new file mode 100644 index 00000000..f339de4a --- /dev/null +++ b/algonaut_algod/src/models/get_block_200_response.rs @@ -0,0 +1,25 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct GetBlock200Response { + /// Block header data. + #[serde(rename = "block")] + pub block: serde_json::Value, + /// Optional certificate object. This is only included when the format is set to message pack. + #[serde(rename = "cert", skip_serializing_if = "Option::is_none")] + pub cert: Option, +} + +impl GetBlock200Response { + pub fn new(block: serde_json::Value) -> GetBlock200Response { + GetBlock200Response { block, cert: None } + } +} diff --git a/algonaut_algod/src/models/get_block_hash_200_response.rs b/algonaut_algod/src/models/get_block_hash_200_response.rs new file mode 100644 index 00000000..5c888038 --- /dev/null +++ b/algonaut_algod/src/models/get_block_hash_200_response.rs @@ -0,0 +1,22 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct GetBlockHash200Response { + /// Block header hash. + #[serde(rename = "blockHash")] + pub block_hash: String, +} + +impl GetBlockHash200Response { + pub fn new(block_hash: String) -> GetBlockHash200Response { + GetBlockHash200Response { block_hash } + } +} diff --git a/algonaut_algod/src/models/get_pending_transactions_by_address_200_response.rs b/algonaut_algod/src/models/get_pending_transactions_by_address_200_response.rs new file mode 100644 index 00000000..7c0d6dba --- /dev/null +++ b/algonaut_algod/src/models/get_pending_transactions_by_address_200_response.rs @@ -0,0 +1,34 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +/// GetPendingTransactionsByAddress200Response : PendingTransactions is an array of signed transactions exactly as they were submitted. + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct GetPendingTransactionsByAddress200Response { + /// An array of signed transaction objects. + #[serde(rename = "top-transactions")] + pub top_transactions: Vec, + /// Total number of transactions in the pool. + #[serde(rename = "total-transactions")] + pub total_transactions: u64, +} + +impl GetPendingTransactionsByAddress200Response { + /// PendingTransactions is an array of signed transactions exactly as they were submitted. + pub fn new( + top_transactions: Vec, + total_transactions: u64, + ) -> GetPendingTransactionsByAddress200Response { + GetPendingTransactionsByAddress200Response { + top_transactions, + total_transactions, + } + } +} diff --git a/algonaut_algod/src/models/get_status_200_response.rs b/algonaut_algod/src/models/get_status_200_response.rs new file mode 100644 index 00000000..2b143190 --- /dev/null +++ b/algonaut_algod/src/models/get_status_200_response.rs @@ -0,0 +1,170 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +/// GetStatus200Response : NodeStatus contains the information about a node status + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct GetStatus200Response { + /// The current catchpoint that is being caught up to + #[serde(rename = "catchpoint", skip_serializing_if = "Option::is_none")] + pub catchpoint: Option, + /// The number of blocks that have already been obtained by the node as part of the catchup + #[serde( + rename = "catchpoint-acquired-blocks", + skip_serializing_if = "Option::is_none" + )] + pub catchpoint_acquired_blocks: Option, + /// The number of accounts from the current catchpoint that have been processed so far as part of the catchup + #[serde( + rename = "catchpoint-processed-accounts", + skip_serializing_if = "Option::is_none" + )] + pub catchpoint_processed_accounts: Option, + /// The number of key-values (KVs) from the current catchpoint that have been processed so far as part of the catchup + #[serde( + rename = "catchpoint-processed-kvs", + skip_serializing_if = "Option::is_none" + )] + pub catchpoint_processed_kvs: Option, + /// The total number of accounts included in the current catchpoint + #[serde( + rename = "catchpoint-total-accounts", + skip_serializing_if = "Option::is_none" + )] + pub catchpoint_total_accounts: Option, + /// The total number of blocks that are required to complete the current catchpoint catchup + #[serde( + rename = "catchpoint-total-blocks", + skip_serializing_if = "Option::is_none" + )] + pub catchpoint_total_blocks: Option, + /// The total number of key-values (KVs) included in the current catchpoint + #[serde( + rename = "catchpoint-total-kvs", + skip_serializing_if = "Option::is_none" + )] + pub catchpoint_total_kvs: Option, + /// The number of accounts from the current catchpoint that have been verified so far as part of the catchup + #[serde( + rename = "catchpoint-verified-accounts", + skip_serializing_if = "Option::is_none" + )] + pub catchpoint_verified_accounts: Option, + /// The number of key-values (KVs) from the current catchpoint that have been verified so far as part of the catchup + #[serde( + rename = "catchpoint-verified-kvs", + skip_serializing_if = "Option::is_none" + )] + pub catchpoint_verified_kvs: Option, + /// CatchupTime in nanoseconds + #[serde(rename = "catchup-time")] + pub catchup_time: u64, + /// The last catchpoint seen by the node + #[serde(rename = "last-catchpoint", skip_serializing_if = "Option::is_none")] + pub last_catchpoint: Option, + /// LastRound indicates the last round seen + #[serde(rename = "last-round")] + pub last_round: u64, + /// LastVersion indicates the last consensus version supported + #[serde(rename = "last-version")] + pub last_version: String, + /// NextVersion of consensus protocol to use + #[serde(rename = "next-version")] + pub next_version: String, + /// NextVersionRound is the round at which the next consensus version will apply + #[serde(rename = "next-version-round")] + pub next_version_round: u64, + /// NextVersionSupported indicates whether the next consensus version is supported by this node + #[serde(rename = "next-version-supported")] + pub next_version_supported: bool, + /// StoppedAtUnsupportedRound indicates that the node does not support the new rounds and has stopped making progress + #[serde(rename = "stopped-at-unsupported-round")] + pub stopped_at_unsupported_round: bool, + /// TimeSinceLastRound in nanoseconds + #[serde(rename = "time-since-last-round")] + pub time_since_last_round: u64, + /// Upgrade delay + #[serde(rename = "upgrade-delay", skip_serializing_if = "Option::is_none")] + pub upgrade_delay: Option, + /// Next protocol round + #[serde( + rename = "upgrade-next-protocol-vote-before", + skip_serializing_if = "Option::is_none" + )] + pub upgrade_next_protocol_vote_before: Option, + /// No votes cast for consensus upgrade + #[serde(rename = "upgrade-no-votes", skip_serializing_if = "Option::is_none")] + pub upgrade_no_votes: Option, + /// This node's upgrade vote + #[serde(rename = "upgrade-node-vote", skip_serializing_if = "Option::is_none")] + pub upgrade_node_vote: Option, + /// Total voting rounds for current upgrade + #[serde( + rename = "upgrade-vote-rounds", + skip_serializing_if = "Option::is_none" + )] + pub upgrade_vote_rounds: Option, + /// Total votes cast for consensus upgrade + #[serde(rename = "upgrade-votes", skip_serializing_if = "Option::is_none")] + pub upgrade_votes: Option, + /// Yes votes required for consensus upgrade + #[serde( + rename = "upgrade-votes-required", + skip_serializing_if = "Option::is_none" + )] + pub upgrade_votes_required: Option, + /// Yes votes cast for consensus upgrade + #[serde(rename = "upgrade-yes-votes", skip_serializing_if = "Option::is_none")] + pub upgrade_yes_votes: Option, +} + +#[allow(clippy::too_many_arguments)] +impl GetStatus200Response { + /// NodeStatus contains the information about a node status + pub fn new( + catchup_time: u64, + last_round: u64, + last_version: String, + next_version: String, + next_version_round: u64, + next_version_supported: bool, + stopped_at_unsupported_round: bool, + time_since_last_round: u64, + ) -> GetStatus200Response { + GetStatus200Response { + catchpoint: None, + catchpoint_acquired_blocks: None, + catchpoint_processed_accounts: None, + catchpoint_processed_kvs: None, + catchpoint_total_accounts: None, + catchpoint_total_blocks: None, + catchpoint_total_kvs: None, + catchpoint_verified_accounts: None, + catchpoint_verified_kvs: None, + catchup_time, + last_catchpoint: None, + last_round, + last_version, + next_version, + next_version_round, + next_version_supported, + stopped_at_unsupported_round, + time_since_last_round, + upgrade_delay: None, + upgrade_next_protocol_vote_before: None, + upgrade_no_votes: None, + upgrade_node_vote: None, + upgrade_vote_rounds: None, + upgrade_votes: None, + upgrade_votes_required: None, + upgrade_yes_votes: None, + } + } +} diff --git a/algonaut_algod/src/models/get_supply_200_response.rs b/algonaut_algod/src/models/get_supply_200_response.rs new file mode 100644 index 00000000..b0c8e4be --- /dev/null +++ b/algonaut_algod/src/models/get_supply_200_response.rs @@ -0,0 +1,35 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +/// GetSupply200Response : Supply represents the current supply of MicroAlgos in the system + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct GetSupply200Response { + /// Round + #[serde(rename = "current_round")] + pub current_round: u64, + /// OnlineMoney + #[serde(rename = "online-money")] + pub online_money: u64, + /// TotalMoney + #[serde(rename = "total-money")] + pub total_money: u64, +} + +impl GetSupply200Response { + /// Supply represents the current supply of MicroAlgos in the system + pub fn new(current_round: u64, online_money: u64, total_money: u64) -> GetSupply200Response { + GetSupply200Response { + current_round, + online_money, + total_money, + } + } +} diff --git a/algonaut_algod/src/models/get_sync_round_200_response.rs b/algonaut_algod/src/models/get_sync_round_200_response.rs new file mode 100644 index 00000000..bbed5db3 --- /dev/null +++ b/algonaut_algod/src/models/get_sync_round_200_response.rs @@ -0,0 +1,22 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct GetSyncRound200Response { + /// The minimum sync round for the ledger. + #[serde(rename = "round")] + pub round: u64, +} + +impl GetSyncRound200Response { + pub fn new(round: u64) -> GetSyncRound200Response { + GetSyncRound200Response { round } + } +} diff --git a/algonaut_algod/src/models/get_transaction_proof_200_response.rs b/algonaut_algod/src/models/get_transaction_proof_200_response.rs new file mode 100644 index 00000000..9bef71ed --- /dev/null +++ b/algonaut_algod/src/models/get_transaction_proof_200_response.rs @@ -0,0 +1,63 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +use algonaut_encoding::Bytes; + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct GetTransactionProof200Response { + /// The type of hash function used to create the proof, must be one of: * sha512_256 * sha256 + #[serde(rename = "hashtype")] + pub hashtype: Hashtype, + /// Index of the transaction in the block's payset. + #[serde(rename = "idx")] + pub idx: u64, + /// Proof of transaction membership. + #[serde(rename = "proof")] + pub proof: Bytes, + /// Hash of SignedTxnInBlock for verifying proof. + #[serde(rename = "stibhash")] + pub stibhash: Bytes, + /// Represents the depth of the tree that is being proven, i.e. the number of edges from a leaf to the root. + #[serde(rename = "treedepth")] + pub treedepth: u64, +} + +impl GetTransactionProof200Response { + pub fn new( + hashtype: Hashtype, + idx: u64, + proof: Bytes, + stibhash: Bytes, + treedepth: u64, + ) -> GetTransactionProof200Response { + GetTransactionProof200Response { + hashtype, + idx, + proof, + stibhash, + treedepth, + } + } +} + +/// The type of hash function used to create the proof, must be one of: * sha512_256 * sha256 +#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] +pub enum Hashtype { + #[serde(rename = "sha512_256")] + Sha512256, + #[serde(rename = "sha256")] + Sha256, +} + +impl Default for Hashtype { + fn default() -> Hashtype { + Self::Sha512256 + } +} diff --git a/algonaut_algod/src/models/kv_delta.rs b/algonaut_algod/src/models/kv_delta.rs new file mode 100644 index 00000000..03253e1c --- /dev/null +++ b/algonaut_algod/src/models/kv_delta.rs @@ -0,0 +1,33 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +use algonaut_encoding::Bytes; + +/// KvDelta : A single Delta containing the key, the previous value and the current value for a single round. + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct KvDelta { + /// The key, base64 encoded. + #[serde(rename = "key", skip_serializing_if = "Option::is_none")] + pub key: Option, + /// The new value of the KV store entry, base64 encoded. + #[serde(rename = "value", skip_serializing_if = "Option::is_none")] + pub value: Option, +} + +impl KvDelta { + /// A single Delta containing the key, the previous value and the current value for a single round. + pub fn new() -> KvDelta { + KvDelta { + key: None, + value: None, + } + } +} diff --git a/algonaut_algod/src/models/light_block_header_proof.rs b/algonaut_algod/src/models/light_block_header_proof.rs new file mode 100644 index 00000000..1d72f326 --- /dev/null +++ b/algonaut_algod/src/models/light_block_header_proof.rs @@ -0,0 +1,37 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +use algonaut_encoding::Bytes; + +/// LightBlockHeaderProof : Proof of membership and position of a light block header. + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct LightBlockHeaderProof { + /// The index of the light block header in the vector commitment tree + #[serde(rename = "index")] + pub index: u64, + /// The encoded proof. + #[serde(rename = "proof")] + pub proof: Bytes, + /// Represents the depth of the tree that is being proven, i.e. the number of edges from a leaf to the root. + #[serde(rename = "treedepth")] + pub treedepth: u64, +} + +impl LightBlockHeaderProof { + /// Proof of membership and position of a light block header. + pub fn new(index: u64, proof: Bytes, treedepth: u64) -> LightBlockHeaderProof { + LightBlockHeaderProof { + index, + proof, + treedepth, + } + } +} diff --git a/algonaut_algod/src/models/mod.rs b/algonaut_algod/src/models/mod.rs new file mode 100644 index 00000000..89ad38b8 --- /dev/null +++ b/algonaut_algod/src/models/mod.rs @@ -0,0 +1,104 @@ +pub mod abort_catchup_200_response; +pub use self::abort_catchup_200_response::AbortCatchup200Response; +pub mod account; +pub use self::account::Account; +pub mod account_application_information_200_response; +pub use self::account_application_information_200_response::AccountApplicationInformation200Response; +pub mod account_asset_information_200_response; +pub use self::account_asset_information_200_response::AccountAssetInformation200Response; +pub mod account_participation; +pub use self::account_participation::AccountParticipation; +pub mod account_state_delta; +pub use self::account_state_delta::AccountStateDelta; +pub mod add_participation_key_200_response; +pub use self::add_participation_key_200_response::AddParticipationKey200Response; +pub mod application; +pub use self::application::Application; +pub mod application_local_state; +pub use self::application_local_state::ApplicationLocalState; +pub mod application_params; +pub use self::application_params::ApplicationParams; +pub mod application_state_schema; +pub use self::application_state_schema::ApplicationStateSchema; +pub mod asset; +pub use self::asset::Asset; +pub mod asset_holding; +pub use self::asset_holding::AssetHolding; +pub mod asset_params; +pub use self::asset_params::AssetParams; +pub mod model_box; +pub use self::model_box::Box; +pub mod box_descriptor; +pub use self::box_descriptor::BoxDescriptor; +pub mod build_version; +pub use self::build_version::BuildVersion; +pub mod dryrun_request; +pub use self::dryrun_request::DryrunRequest; +pub mod dryrun_source; +pub use self::dryrun_source::DryrunSource; +pub mod dryrun_state; +pub use self::dryrun_state::DryrunState; +pub mod dryrun_txn_result; +pub use self::dryrun_txn_result::DryrunTxnResult; +pub mod error_response; +pub use self::error_response::ErrorResponse; +pub mod eval_delta; +pub use self::eval_delta::EvalDelta; +pub mod eval_delta_key_value; +pub use self::eval_delta_key_value::EvalDeltaKeyValue; +pub mod get_application_boxes_200_response; +pub use self::get_application_boxes_200_response::GetApplicationBoxes200Response; +pub mod get_block_200_response; +pub use self::get_block_200_response::GetBlock200Response; +pub mod get_block_hash_200_response; +pub use self::get_block_hash_200_response::GetBlockHash200Response; +pub mod get_pending_transactions_by_address_200_response; +pub use self::get_pending_transactions_by_address_200_response::GetPendingTransactionsByAddress200Response; +pub mod get_status_200_response; +pub use self::get_status_200_response::GetStatus200Response; +pub mod get_supply_200_response; +pub use self::get_supply_200_response::GetSupply200Response; +pub mod get_sync_round_200_response; +pub use self::get_sync_round_200_response::GetSyncRound200Response; +pub mod get_transaction_proof_200_response; +pub use self::get_transaction_proof_200_response::GetTransactionProof200Response; +pub mod kv_delta; +pub use self::kv_delta::KvDelta; +pub mod light_block_header_proof; +pub use self::light_block_header_proof::LightBlockHeaderProof; +pub mod participation_key; +pub use self::participation_key::ParticipationKey; +pub mod pending_transaction_response; +pub use self::pending_transaction_response::PendingTransactionResponse; +pub mod raw_transaction_200_response; +pub use self::raw_transaction_200_response::RawTransaction200Response; +pub mod simulate_request; +pub use self::simulate_request::SimulateRequest; +pub mod simulate_request_transaction_group; +pub use self::simulate_request_transaction_group::SimulateRequestTransactionGroup; +pub mod simulate_transaction_200_response; +pub use self::simulate_transaction_200_response::SimulateTransaction200Response; +pub mod simulate_transaction_group_result; +pub use self::simulate_transaction_group_result::SimulateTransactionGroupResult; +pub mod simulate_transaction_result; +pub use self::simulate_transaction_result::SimulateTransactionResult; +pub mod start_catchup_200_response; +pub use self::start_catchup_200_response::StartCatchup200Response; +pub mod state_proof; +pub use self::state_proof::StateProof; +pub mod state_proof_message; +pub use self::state_proof_message::StateProofMessage; +pub mod teal_compile_200_response; +pub use self::teal_compile_200_response::TealCompile200Response; +pub mod teal_disassemble_200_response; +pub use self::teal_disassemble_200_response::TealDisassemble200Response; +pub mod teal_dryrun_200_response; +pub use self::teal_dryrun_200_response::TealDryrun200Response; +pub mod teal_key_value; +pub use self::teal_key_value::TealKeyValue; +pub mod teal_value; +pub use self::teal_value::TealValue; +pub mod transaction_params_200_response; +pub use self::transaction_params_200_response::TransactionParams200Response; +pub mod version; +pub use self::version::Version; diff --git a/algonaut_algod/src/models/model_box.rs b/algonaut_algod/src/models/model_box.rs new file mode 100644 index 00000000..04bbf37f --- /dev/null +++ b/algonaut_algod/src/models/model_box.rs @@ -0,0 +1,30 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +use algonaut_encoding::Bytes; + +/// Box : Box name and its content. + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct Box { + /// \\[name\\] box name, base64 encoded + #[serde(rename = "name")] + pub name: Bytes, + /// \\[value\\] box value, base64 encoded. + #[serde(rename = "value")] + pub value: Bytes, +} + +impl Box { + /// Box name and its content. + pub fn new(name: Bytes, value: Bytes) -> Box { + Box { name, value } + } +} diff --git a/algonaut_algod/src/models/participation_key.rs b/algonaut_algod/src/models/participation_key.rs new file mode 100644 index 00000000..1d950ae5 --- /dev/null +++ b/algonaut_algod/src/models/participation_key.rs @@ -0,0 +1,67 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +/// ParticipationKey : Represents a participation key used by the node. + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct ParticipationKey { + /// Address the key was generated for. + #[serde(rename = "address")] + pub address: String, + /// When registered, this is the first round it may be used. + #[serde( + rename = "effective-first-valid", + skip_serializing_if = "Option::is_none" + )] + pub effective_first_valid: Option, + /// When registered, this is the last round it may be used. + #[serde( + rename = "effective-last-valid", + skip_serializing_if = "Option::is_none" + )] + pub effective_last_valid: Option, + /// The key's ParticipationID. + #[serde(rename = "id")] + pub id: String, + #[serde(rename = "key")] + pub key: Box, + /// Round when this key was last used to propose a block. + #[serde( + rename = "last-block-proposal", + skip_serializing_if = "Option::is_none" + )] + pub last_block_proposal: Option, + /// Round when this key was last used to generate a state proof. + #[serde(rename = "last-state-proof", skip_serializing_if = "Option::is_none")] + pub last_state_proof: Option, + /// Round when this key was last used to vote. + #[serde(rename = "last-vote", skip_serializing_if = "Option::is_none")] + pub last_vote: Option, +} + +impl ParticipationKey { + /// Represents a participation key used by the node. + pub fn new( + address: String, + id: String, + key: crate::models::AccountParticipation, + ) -> ParticipationKey { + ParticipationKey { + address, + effective_first_valid: None, + effective_last_valid: None, + id, + key: Box::new(key), + last_block_proposal: None, + last_state_proof: None, + last_vote: None, + } + } +} diff --git a/algonaut_algod/src/models/pending_transaction_response.rs b/algonaut_algod/src/models/pending_transaction_response.rs new file mode 100644 index 00000000..e2c8b663 --- /dev/null +++ b/algonaut_algod/src/models/pending_transaction_response.rs @@ -0,0 +1,84 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +use algonaut_encoding::Bytes; + +/// PendingTransactionResponse : Details about a pending transaction. If the transaction was recently confirmed, includes confirmation details like the round and reward details. + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct PendingTransactionResponse { + /// The application index if the transaction was found and it created an application. + #[serde(rename = "application-index", skip_serializing_if = "Option::is_none")] + pub application_index: Option, + /// The number of the asset's unit that were transferred to the close-to address. + #[serde( + rename = "asset-closing-amount", + skip_serializing_if = "Option::is_none" + )] + pub asset_closing_amount: Option, + /// The asset index if the transaction was found and it created an asset. + #[serde(rename = "asset-index", skip_serializing_if = "Option::is_none")] + pub asset_index: Option, + /// Rewards in microalgos applied to the close remainder to account. + #[serde(rename = "close-rewards", skip_serializing_if = "Option::is_none")] + pub close_rewards: Option, + /// Closing amount for the transaction. + #[serde(rename = "closing-amount", skip_serializing_if = "Option::is_none")] + pub closing_amount: Option, + /// The round where this transaction was confirmed, if present. + #[serde(rename = "confirmed-round", skip_serializing_if = "Option::is_none")] + pub confirmed_round: Option, + /// Application state delta. + #[serde(rename = "global-state-delta", skip_serializing_if = "Option::is_none")] + pub global_state_delta: Option>, + /// Inner transactions produced by application execution. + #[serde(rename = "inner-txns", skip_serializing_if = "Option::is_none")] + pub inner_txns: Option>, + /// Local state key/value changes for the application being executed by this transaction. + #[serde(rename = "local-state-delta", skip_serializing_if = "Option::is_none")] + pub local_state_delta: Option>, + /// Logs for the application being executed by this transaction. + #[serde(rename = "logs", skip_serializing_if = "Option::is_none")] + pub logs: Option>, + /// Indicates that the transaction was kicked out of this node's transaction pool (and specifies why that happened). An empty string indicates the transaction wasn't kicked out of this node's txpool due to an error. + #[serde(rename = "pool-error")] + pub pool_error: String, + /// Rewards in microalgos applied to the receiver account. + #[serde(rename = "receiver-rewards", skip_serializing_if = "Option::is_none")] + pub receiver_rewards: Option, + /// Rewards in microalgos applied to the sender account. + #[serde(rename = "sender-rewards", skip_serializing_if = "Option::is_none")] + pub sender_rewards: Option, + /// The raw signed transaction. + #[serde(rename = "txn")] + pub txn: serde_json::Value, +} + +impl PendingTransactionResponse { + /// Details about a pending transaction. If the transaction was recently confirmed, includes confirmation details like the round and reward details. + pub fn new(pool_error: String, txn: serde_json::Value) -> PendingTransactionResponse { + PendingTransactionResponse { + application_index: None, + asset_closing_amount: None, + asset_index: None, + close_rewards: None, + closing_amount: None, + confirmed_round: None, + global_state_delta: None, + inner_txns: None, + local_state_delta: None, + logs: None, + pool_error, + receiver_rewards: None, + sender_rewards: None, + txn, + } + } +} diff --git a/algonaut_algod/src/models/raw_transaction_200_response.rs b/algonaut_algod/src/models/raw_transaction_200_response.rs new file mode 100644 index 00000000..1606e0e8 --- /dev/null +++ b/algonaut_algod/src/models/raw_transaction_200_response.rs @@ -0,0 +1,22 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct RawTransaction200Response { + /// encoding of the transaction hash. + #[serde(rename = "txId")] + pub tx_id: String, +} + +impl RawTransaction200Response { + pub fn new(tx_id: String) -> RawTransaction200Response { + RawTransaction200Response { tx_id } + } +} diff --git a/algonaut_algod/src/models/simulate_request.rs b/algonaut_algod/src/models/simulate_request.rs new file mode 100644 index 00000000..33378909 --- /dev/null +++ b/algonaut_algod/src/models/simulate_request.rs @@ -0,0 +1,25 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +/// SimulateRequest : Request type for simulation endpoint. + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct SimulateRequest { + /// The transaction groups to simulate. + #[serde(rename = "txn-groups")] + pub txn_groups: Vec, +} + +impl SimulateRequest { + /// Request type for simulation endpoint. + pub fn new(txn_groups: Vec) -> SimulateRequest { + SimulateRequest { txn_groups } + } +} diff --git a/algonaut_algod/src/models/simulate_request_transaction_group.rs b/algonaut_algod/src/models/simulate_request_transaction_group.rs new file mode 100644 index 00000000..ae942737 --- /dev/null +++ b/algonaut_algod/src/models/simulate_request_transaction_group.rs @@ -0,0 +1,25 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +/// SimulateRequestTransactionGroup : A transaction group to simulate. + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct SimulateRequestTransactionGroup { + /// An atomic transaction group. + #[serde(rename = "txns")] + pub txns: Vec, +} + +impl SimulateRequestTransactionGroup { + /// A transaction group to simulate. + pub fn new(txns: Vec) -> SimulateRequestTransactionGroup { + SimulateRequestTransactionGroup { txns } + } +} diff --git a/algonaut_algod/src/models/simulate_transaction_200_response.rs b/algonaut_algod/src/models/simulate_transaction_200_response.rs new file mode 100644 index 00000000..845d1244 --- /dev/null +++ b/algonaut_algod/src/models/simulate_transaction_200_response.rs @@ -0,0 +1,41 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct SimulateTransaction200Response { + /// The round immediately preceding this simulation. State changes through this round were used to run this simulation. + #[serde(rename = "last-round")] + pub last_round: u64, + /// A result object for each transaction group that was simulated. + #[serde(rename = "txn-groups")] + pub txn_groups: Vec, + /// The version of this response object. + #[serde(rename = "version")] + pub version: u64, + /// Indicates whether the simulated transactions would have succeeded during an actual submission. If any transaction fails or is missing a signature, this will be false. + #[serde(rename = "would-succeed")] + pub would_succeed: bool, +} + +impl SimulateTransaction200Response { + pub fn new( + last_round: u64, + txn_groups: Vec, + version: u64, + would_succeed: bool, + ) -> SimulateTransaction200Response { + SimulateTransaction200Response { + last_round, + txn_groups, + version, + would_succeed, + } + } +} diff --git a/algonaut_algod/src/models/simulate_transaction_group_result.rs b/algonaut_algod/src/models/simulate_transaction_group_result.rs new file mode 100644 index 00000000..877f7242 --- /dev/null +++ b/algonaut_algod/src/models/simulate_transaction_group_result.rs @@ -0,0 +1,48 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +/// SimulateTransactionGroupResult : Simulation result for an atomic transaction group + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct SimulateTransactionGroupResult { + /// Total budget added during execution of app calls in the transaction group. + #[serde(rename = "app-budget-added", skip_serializing_if = "Option::is_none")] + pub app_budget_added: Option, + /// Total budget consumed during execution of app calls in the transaction group. + #[serde( + rename = "app-budget-consumed", + skip_serializing_if = "Option::is_none" + )] + pub app_budget_consumed: Option, + /// If present, indicates which transaction in this group caused the failure. This array represents the path to the failing transaction. Indexes are zero based, the first element indicates the top-level transaction, and successive elements indicate deeper inner transactions. + #[serde(rename = "failed-at", skip_serializing_if = "Option::is_none")] + pub failed_at: Option>, + /// If present, indicates that the transaction group failed and specifies why that happened + #[serde(rename = "failure-message", skip_serializing_if = "Option::is_none")] + pub failure_message: Option, + /// Simulation result for individual transactions + #[serde(rename = "txn-results")] + pub txn_results: Vec, +} + +impl SimulateTransactionGroupResult { + /// Simulation result for an atomic transaction group + pub fn new( + txn_results: Vec, + ) -> SimulateTransactionGroupResult { + SimulateTransactionGroupResult { + app_budget_added: None, + app_budget_consumed: None, + failed_at: None, + failure_message: None, + txn_results, + } + } +} diff --git a/algonaut_algod/src/models/simulate_transaction_result.rs b/algonaut_algod/src/models/simulate_transaction_result.rs new file mode 100644 index 00000000..5a6f581f --- /dev/null +++ b/algonaut_algod/src/models/simulate_transaction_result.rs @@ -0,0 +1,44 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +/// SimulateTransactionResult : Simulation result for an individual transaction + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct SimulateTransactionResult { + /// Budget used during execution of an app call transaction. This value includes budged used by inner app calls spawned by this transaction. + #[serde( + rename = "app-budget-consumed", + skip_serializing_if = "Option::is_none" + )] + pub app_budget_consumed: Option, + /// Budget used during execution of a logic sig transaction. + #[serde( + rename = "logic-sig-budget-consumed", + skip_serializing_if = "Option::is_none" + )] + pub logic_sig_budget_consumed: Option, + /// A boolean indicating whether this transaction is missing signatures + #[serde(rename = "missing-signature", skip_serializing_if = "Option::is_none")] + pub missing_signature: Option, + #[serde(rename = "txn-result")] + pub txn_result: Box, +} + +impl SimulateTransactionResult { + /// Simulation result for an individual transaction + pub fn new(txn_result: crate::models::PendingTransactionResponse) -> SimulateTransactionResult { + SimulateTransactionResult { + app_budget_consumed: None, + logic_sig_budget_consumed: None, + missing_signature: None, + txn_result: Box::new(txn_result), + } + } +} diff --git a/algonaut_algod/src/models/start_catchup_200_response.rs b/algonaut_algod/src/models/start_catchup_200_response.rs new file mode 100644 index 00000000..25eeca0a --- /dev/null +++ b/algonaut_algod/src/models/start_catchup_200_response.rs @@ -0,0 +1,25 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +/// StartCatchup200Response : An catchpoint start response. + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct StartCatchup200Response { + /// Catchup start response string + #[serde(rename = "catchup-message")] + pub catchup_message: String, +} + +impl StartCatchup200Response { + /// An catchpoint start response. + pub fn new(catchup_message: String) -> StartCatchup200Response { + StartCatchup200Response { catchup_message } + } +} diff --git a/algonaut_algod/src/models/state_proof.rs b/algonaut_algod/src/models/state_proof.rs new file mode 100644 index 00000000..de329214 --- /dev/null +++ b/algonaut_algod/src/models/state_proof.rs @@ -0,0 +1,32 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +use algonaut_encoding::Bytes; + +/// StateProof : Represents a state proof and its corresponding message + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct StateProof { + #[serde(rename = "Message")] + pub message: Box, + /// The encoded StateProof for the message. + #[serde(rename = "StateProof")] + pub state_proof: Bytes, +} + +impl StateProof { + /// Represents a state proof and its corresponding message + pub fn new(message: crate::models::StateProofMessage, state_proof: Bytes) -> StateProof { + StateProof { + message: Box::new(message), + state_proof, + } + } +} diff --git a/algonaut_algod/src/models/state_proof_message.rs b/algonaut_algod/src/models/state_proof_message.rs new file mode 100644 index 00000000..d2e4f2dc --- /dev/null +++ b/algonaut_algod/src/models/state_proof_message.rs @@ -0,0 +1,51 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +use algonaut_encoding::Bytes; + +/// StateProofMessage : Represents the message that the state proofs are attesting to. + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct StateProofMessage { + /// The vector commitment root on all light block headers within a state proof interval. + #[serde(rename = "BlockHeadersCommitment")] + pub block_headers_commitment: Bytes, + /// The first round the message attests to. + #[serde(rename = "FirstAttestedRound")] + pub first_attested_round: u64, + /// The last round the message attests to. + #[serde(rename = "LastAttestedRound")] + pub last_attested_round: u64, + /// An integer value representing the natural log of the proven weight with 16 bits of precision. This value would be used to verify the next state proof. + #[serde(rename = "LnProvenWeight")] + pub ln_proven_weight: u64, + /// The vector commitment root of the top N accounts to sign the next StateProof. + #[serde(rename = "VotersCommitment")] + pub voters_commitment: Bytes, +} + +impl StateProofMessage { + /// Represents the message that the state proofs are attesting to. + pub fn new( + block_headers_commitment: Bytes, + first_attested_round: u64, + last_attested_round: u64, + ln_proven_weight: u64, + voters_commitment: Bytes, + ) -> StateProofMessage { + StateProofMessage { + block_headers_commitment, + first_attested_round, + last_attested_round, + ln_proven_weight, + voters_commitment, + } + } +} diff --git a/algonaut_algod/src/models/teal_compile_200_response.rs b/algonaut_algod/src/models/teal_compile_200_response.rs new file mode 100644 index 00000000..67790999 --- /dev/null +++ b/algonaut_algod/src/models/teal_compile_200_response.rs @@ -0,0 +1,32 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct TealCompile200Response { + /// base32 SHA512_256 of program bytes (Address style) + #[serde(rename = "hash")] + pub hash: String, + /// base64 encoded program bytes + #[serde(rename = "result")] + pub result: String, + /// JSON of the source map + #[serde(rename = "sourcemap", skip_serializing_if = "Option::is_none")] + pub sourcemap: Option, +} + +impl TealCompile200Response { + pub fn new(hash: String, result: String) -> TealCompile200Response { + TealCompile200Response { + hash, + result, + sourcemap: None, + } + } +} diff --git a/algonaut_algod/src/models/teal_disassemble_200_response.rs b/algonaut_algod/src/models/teal_disassemble_200_response.rs new file mode 100644 index 00000000..5cb4fa60 --- /dev/null +++ b/algonaut_algod/src/models/teal_disassemble_200_response.rs @@ -0,0 +1,22 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct TealDisassemble200Response { + /// disassembled Teal code + #[serde(rename = "result")] + pub result: String, +} + +impl TealDisassemble200Response { + pub fn new(result: String) -> TealDisassemble200Response { + TealDisassemble200Response { result } + } +} diff --git a/algonaut_algod/src/models/teal_dryrun_200_response.rs b/algonaut_algod/src/models/teal_dryrun_200_response.rs new file mode 100644 index 00000000..c5d2952b --- /dev/null +++ b/algonaut_algod/src/models/teal_dryrun_200_response.rs @@ -0,0 +1,34 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct TealDryrun200Response { + #[serde(rename = "error")] + pub error: String, + /// Protocol version is the protocol version Dryrun was operated under. + #[serde(rename = "protocol-version")] + pub protocol_version: String, + #[serde(rename = "txns")] + pub txns: Vec, +} + +impl TealDryrun200Response { + pub fn new( + error: String, + protocol_version: String, + txns: Vec, + ) -> TealDryrun200Response { + TealDryrun200Response { + error, + protocol_version, + txns, + } + } +} diff --git a/algonaut_algod/src/models/teal_key_value.rs b/algonaut_algod/src/models/teal_key_value.rs new file mode 100644 index 00000000..f1ab9daa --- /dev/null +++ b/algonaut_algod/src/models/teal_key_value.rs @@ -0,0 +1,29 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +/// TealKeyValue : Represents a key-value pair in an application store. + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct TealKeyValue { + #[serde(rename = "key")] + pub key: String, + #[serde(rename = "value")] + pub value: Box, +} + +impl TealKeyValue { + /// Represents a key-value pair in an application store. + pub fn new(key: String, value: crate::models::TealValue) -> TealKeyValue { + TealKeyValue { + key, + value: Box::new(value), + } + } +} diff --git a/algonaut_algod/src/models/teal_value.rs b/algonaut_algod/src/models/teal_value.rs new file mode 100644 index 00000000..b0c58db6 --- /dev/null +++ b/algonaut_algod/src/models/teal_value.rs @@ -0,0 +1,41 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +use algonaut_encoding::deserialize_bytes; + +/// TealValue : Represents a TEAL value. + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct TealValue { + /// \\[tb\\] bytes value. + #[serde( + rename = "bytes", + skip_serializing_if = "Vec::is_empty", + deserialize_with = "deserialize_bytes" + )] + pub bytes: Vec, + /// \\[tt\\] value type. Value `1` refers to **bytes**, value `2` refers to **uint** + #[serde(rename = "type")] + pub value_type: u64, + /// \\[ui\\] uint value. + #[serde(rename = "uint")] + pub uint: u64, +} + +impl TealValue { + /// Represents a TEAL value. + pub fn new(bytes: Vec, value_type: u64, uint: u64) -> TealValue { + TealValue { + bytes, + value_type, + uint, + } + } +} diff --git a/algonaut_algod/src/models/transaction_params_200_response.rs b/algonaut_algod/src/models/transaction_params_200_response.rs new file mode 100644 index 00000000..e58baa66 --- /dev/null +++ b/algonaut_algod/src/models/transaction_params_200_response.rs @@ -0,0 +1,56 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +use algonaut_crypto::{deserialize_hash, HashDigest}; + +/// TransactionParams200Response : TransactionParams contains the parameters that help a client construct a new transaction. + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct TransactionParams200Response { + /// ConsensusVersion indicates the consensus protocol version as of LastRound. + #[serde(rename = "consensus-version")] + pub consensus_version: String, + /// Fee is the suggested transaction fee Fee is in units of micro-Algos per byte. Fee may fall to zero but transactions must still have a fee of at least MinTxnFee for the current network protocol. + #[serde(rename = "fee")] + pub fee: u64, + /// GenesisHash is the hash of the genesis block. + #[serde(rename = "genesis-hash", deserialize_with = "deserialize_hash")] + pub genesis_hash: HashDigest, + /// GenesisID is an ID listed in the genesis block. + #[serde(rename = "genesis-id")] + pub genesis_id: String, + /// LastRound indicates the last round seen + #[serde(rename = "last-round")] + pub last_round: u64, + /// The minimum transaction fee (not per byte) required for the txn to validate for the current network protocol. + #[serde(rename = "min-fee")] + pub min_fee: u64, +} + +impl TransactionParams200Response { + /// TransactionParams contains the parameters that help a client construct a new transaction. + pub fn new( + consensus_version: String, + fee: u64, + genesis_hash: HashDigest, + genesis_id: String, + last_round: u64, + min_fee: u64, + ) -> TransactionParams200Response { + TransactionParams200Response { + consensus_version, + fee, + genesis_hash, + genesis_id, + last_round, + min_fee, + } + } +} diff --git a/algonaut_algod/src/models/version.rs b/algonaut_algod/src/models/version.rs new file mode 100644 index 00000000..30a963e8 --- /dev/null +++ b/algonaut_algod/src/models/version.rs @@ -0,0 +1,42 @@ +/* + * Algod REST API. + * + * API endpoint for algod operations. + * + * The version of the OpenAPI document: 0.0.1 + * Contact: contact@algorand.com + * Generated by: https://openapi-generator.tech + */ + +use algonaut_encoding::Bytes; + +/// Version : algod version information. + +#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] +pub struct Version { + #[serde(rename = "build")] + pub build: Box, + #[serde(rename = "genesis_hash_b64")] + pub genesis_hash_b64: Bytes, + #[serde(rename = "genesis_id")] + pub genesis_id: String, + #[serde(rename = "versions")] + pub versions: Vec, +} + +impl Version { + /// algod version information. + pub fn new( + build: crate::models::BuildVersion, + genesis_hash_b64: Bytes, + genesis_id: String, + versions: Vec, + ) -> Version { + Version { + build: Box::new(build), + genesis_hash_b64, + genesis_id, + versions, + } + } +} diff --git a/algonaut_client/src/algod/v2/mod.rs b/algonaut_client/src/algod/v2/mod.rs deleted file mode 100644 index 79b3a770..00000000 --- a/algonaut_client/src/algod/v2/mod.rs +++ /dev/null @@ -1,406 +0,0 @@ -use crate::error::ClientError; -use crate::extensions::reqwest::{to_header_map, ResponseExt}; -use crate::Headers; -use algonaut_core::{Address, Round}; -use algonaut_model::algod::v2::{ - Account, ApiCompiledTeal, Application, Asset, Block, BlockWithCertificate, Catchup, - DryrunResponse, GenesisBlock, KeyRegistration, NodeStatus, PendingTransaction, - PendingTransactions, Supply, TransactionParams, TransactionResponse, Version, -}; -use reqwest::header::HeaderMap; -use reqwest::Url; - -#[derive(Debug, Clone)] -/// Client for interacting with the Algorand protocol daemon -pub struct Client { - url: String, - headers: HeaderMap, - http_client: reqwest::Client, -} - -impl Client { - pub fn new(url: &str, headers: Headers) -> Result { - Ok(Client { - url: Url::parse(url)?.as_ref().into(), - headers: to_header_map(headers)?, - http_client: reqwest::Client::new(), - }) - } - - pub async fn genesis(&self) -> Result { - let response = self - .http_client - .get(&format!("{}genesis", self.url)) - .headers(self.headers.clone()) - .send() - .await? - .http_error_for_status() - .await? - .json() - .await?; - - Ok(response) - } - - pub async fn health(&self) -> Result<(), ClientError> { - let _ = self - .http_client - .get(&format!("{}health", self.url)) - .headers(self.headers.clone()) - .send() - .await? - .http_error_for_status() - .await?; - - Ok(()) - } - - pub async fn metrics(&self) -> Result { - let response = self - .http_client - .get(&format!("{}metrics", self.url)) - .headers(self.headers.clone()) - .send() - .await? - .http_error_for_status() - .await? - .text() - .await?; - - Ok(response) - } - - pub async fn account_information(&self, address: &str) -> Result { - let response = self - .http_client - .get(&format!("{}v2/accounts/{}", self.url, address)) - .headers(self.headers.clone()) - .send() - .await? - .http_error_for_status() - .await? - .json() - .await?; - - Ok(response) - } - - pub async fn pending_transactions_for( - &self, - address: &str, - max: u64, - ) -> Result { - let response = self - .http_client - .get(&format!( - "{}v2/accounts/{}/transactions/pending", - self.url, address, - )) - .headers(self.headers.clone()) - .query(&[("max", max.to_string())]) - .send() - .await? - .http_error_for_status() - .await? - .json() - .await?; - Ok(response) - } - - pub async fn application_information(&self, id: u64) -> Result { - let response = self - .http_client - .get(&format!("{}v2/applications/{}", self.url, id)) - .headers(self.headers.clone()) - .send() - .await? - .http_error_for_status() - .await? - .json() - .await?; - - Ok(response) - } - - pub async fn asset_information(&self, id: u64) -> Result { - let response = self - .http_client - .get(&format!("{}v2/assets/{}", self.url, id)) - .headers(self.headers.clone()) - .send() - .await? - .http_error_for_status() - .await? - .json() - .await?; - - Ok(response) - } - - pub async fn block(&self, round: Round) -> Result { - let response = self - .http_client - .get(&format!("{}v2/blocks/{}", self.url, round)) - .headers(self.headers.clone()) - .send() - .await? - .http_error_for_status() - .await? - .json() - .await?; - - Ok(response) - } - - pub async fn block_with_certificate( - &self, - round: Round, - ) -> Result { - let response_bytes = self - .http_client - .get(&format!("{}v2/blocks/{}?format=msgpack", self.url, round)) - .headers(self.headers.clone()) - .send() - .await? - .http_error_for_status() - .await? - .bytes() - .await?; - - Ok(rmp_serde::from_slice(&response_bytes)?) - } - - pub async fn start_catchup(&self, catchpoint: &str) -> Result { - let response = self - .http_client - .post(&format!("{}v2/catchup/{}", self.url, catchpoint)) - .headers(self.headers.clone()) - .send() - .await? - .http_error_for_status() - .await? - .json() - .await?; - - Ok(response) - } - - pub async fn abort_catchup(&self, catchpoint: &str) -> Result { - let response = self - .http_client - .delete(&format!("{}v2/catchup/{}", self.url, catchpoint)) - .headers(self.headers.clone()) - .send() - .await? - .http_error_for_status() - .await? - .json() - .await?; - - Ok(response) - } - - pub async fn ledger_supply(&self) -> Result { - let response = self - .http_client - .get(&format!("{}v2/ledger/supply", self.url)) - .headers(self.headers.clone()) - .send() - .await? - .http_error_for_status() - .await? - .json() - .await?; - - Ok(response) - } - - pub async fn register_participation_keys( - &self, - address: &Address, - params: &KeyRegistration, - ) -> Result { - let response = self - .http_client - .post(&format!( - "{}v2/register-participation-keys/{}", - self.url, address - )) - .headers(self.headers.clone()) - .query(¶ms) - .send() - .await? - .http_error_for_status() - .await? - .json() - .await?; - - Ok(response) - } - - pub async fn shutdown(&self, timeout: usize) -> Result<(), ClientError> { - self.http_client - .post(&format!("{}v2/shutdown", self.url)) - .headers(self.headers.clone()) - .query(&[("timeout", timeout.to_string())]) - .send() - .await? - .http_error_for_status() - .await? - .json() - .await?; - - Ok(()) - } - - pub async fn status(&self) -> Result { - let response = self - .http_client - .get(&format!("{}v2/status", self.url)) - .headers(self.headers.clone()) - .send() - .await? - .http_error_for_status() - .await? - .json() - .await?; - - Ok(response) - } - - pub async fn status_after_round(&self, round: Round) -> Result { - let response = self - .http_client - .get(&format!( - "{}v2/status/wait-for-block-after/{}", - self.url, round.0 - )) - .headers(self.headers.clone()) - .send() - .await? - .http_error_for_status() - .await? - .json() - .await?; - - Ok(response) - } - - pub async fn compile_teal(&self, teal: Vec) -> Result { - let response = self - .http_client - .post(&format!("{}v2/teal/compile", self.url)) - .headers(self.headers.clone()) - .header("Content-Type", "application/x-binary") - .body(teal) - .send() - .await? - .http_error_for_status() - .await? - .json() - .await?; - - Ok(response) - } - - pub async fn dryrun_teal(&self, req: Vec) -> Result { - let response = self - .http_client - .post(&format!("{}v2/teal/dryrun", self.url)) - .headers(self.headers.clone()) - .header("Content-Type", "application/x-binary") - .body(req) - .send() - .await? - .http_error_for_status() - .await? - .json() - .await?; - - Ok(response) - } - - pub async fn broadcast_raw_transaction( - &self, - rawtxn: &[u8], - ) -> Result { - let response = self - .http_client - .post(&format!("{}v2/transactions", self.url)) - .headers(self.headers.clone()) - .header("Content-Type", "application/x-binary") - .body(rawtxn.to_vec()) - .send() - .await? - .http_error_for_status() - .await? - .json() - .await?; - - Ok(response) - } - - pub async fn transaction_params(&self) -> Result { - let response = self - .http_client - .get(&format!("{}v2/transactions/params", self.url)) - .headers(self.headers.clone()) - .send() - .await? - .http_error_for_status() - .await? - .json() - .await?; - - Ok(response) - } - - pub async fn pending_transactions(&self, max: u64) -> Result { - let response = self - .http_client - .get(&format!("{}v2/transactions/pending", self.url)) - .headers(self.headers.clone()) - .query(&[("max", max.to_string())]) - .send() - .await? - .http_error_for_status() - .await? - .json() - .await?; - - Ok(response) - } - - pub async fn pending_transaction_with_id( - &self, - txid: &str, - ) -> Result { - let response = self - .http_client - .get(&format!("{}v2/transactions/pending/{}", self.url, txid)) - .headers(self.headers.clone()) - .send() - .await? - .http_error_for_status() - .await? - .json() - .await?; - - Ok(response) - } - - pub async fn versions(&self) -> Result { - let response = self - .http_client - .get(&format!("{}versions", self.url)) - .headers(self.headers.clone()) - .send() - .await? - .http_error_for_status() - .await? - .json() - .await?; - - Ok(response) - } -} diff --git a/algonaut_client/src/indexer/mod.rs b/algonaut_client/src/indexer/mod.rs deleted file mode 100644 index 7083bd82..00000000 --- a/algonaut_client/src/indexer/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub mod v2; diff --git a/algonaut_crypto/src/lib.rs b/algonaut_crypto/src/lib.rs index ae6c02d6..84b4bda2 100644 --- a/algonaut_crypto/src/lib.rs +++ b/algonaut_crypto/src/lib.rs @@ -20,7 +20,7 @@ pub enum HashType { } /// A SHA512_256 hash -#[derive(Copy, Clone, Eq, PartialEq)] +#[derive(Copy, Clone, Default, Eq, PartialEq)] pub struct HashDigest(pub [u8; 32]); impl FromStr for HashDigest { @@ -158,6 +158,19 @@ where Ok(HashDigest(deserialize_bytes32(deserializer)?)) } +pub fn deserialize_opt_hash<'de, D>(deserializer: D) -> Result, D::Error> +where + D: Deserializer<'de>, +{ + // TODO needs testing + let hash = deserialize_bytes32(deserializer)?; + if hash == [0; 32] { + Ok(None) + } else { + Ok(Some(HashDigest(hash))) + } +} + pub fn deserialize_mdk<'de, D>(deserializer: D) -> Result where D: Deserializer<'de>, diff --git a/algonaut_encoding/src/lib.rs b/algonaut_encoding/src/lib.rs index 293dd6e8..da932ba5 100644 --- a/algonaut_encoding/src/lib.rs +++ b/algonaut_encoding/src/lib.rs @@ -1,9 +1,19 @@ use data_encoding::BASE64; use serde::de::Error; use serde::de::Visitor; -use serde::{Deserialize, Deserializer, Serializer}; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; use std::convert::TryInto; +/// Convenience newtype for a array of bytes. +#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)] +pub struct Bytes( + #[serde( + skip_serializing_if = "Vec::is_empty", + deserialize_with = "deserialize_bytes" + )] + pub Vec, +); + pub struct SignatureVisitor; impl<'de> Visitor<'de> for SignatureVisitor { @@ -114,3 +124,11 @@ where { slice.try_into().map_err(D::Error::custom) } + +pub fn deserialize_vec_opt_to_vec<'de, D>(deserializer: D) -> Result, D::Error> +where + D: Deserializer<'de>, +{ + let s: Option> = Deserialize::deserialize(deserializer)?; + Ok(s.unwrap_or_default()) +} diff --git a/algonaut_indexer/Cargo.toml b/algonaut_indexer/Cargo.toml new file mode 100644 index 00000000..d3d7611c --- /dev/null +++ b/algonaut_indexer/Cargo.toml @@ -0,0 +1,38 @@ +[package] +authors = [ + "Manuel Mauro ", + "Ivan Schuetz ", +] +description = "API clients for the Algorand blockchain." +edition = "2018" +keywords = ["Algorand", "sdk"] +license = "MIT" +name = "algonaut_indexer" +repository = "https://github.com/manuelmauro/algonaut" +version = "0.4.2" + +[dependencies] +algonaut_model = { path = "../algonaut_model", version = "0.4.2" } +algonaut_core = { path = "../algonaut_core", version = "0.4.2" } +algonaut_crypto = { path = "../algonaut_crypto", version = "0.4.2" } +algonaut_encoding = { path = "../algonaut_encoding", version = "0.4.2" } +data-encoding = "2.3.1" +derive_more = "0.99.13" +reqwest = { version = "0.11", features = ["json"], default-features = false } +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0.40" +thiserror = "1.0.23" +url = "2.2.0" +async-trait = "0.1.50" +rmp-serde = "1.0.0" + +[dev-dependencies] +dotenv = "0.15.0" +rand = "0.8.3" +getrandom = { version = "0.2.2", features = ["js"] } +tokio = { version = "1.6.0", features = ["macros"] } + +[features] +default = ["native"] +rustls = ["reqwest/rustls-tls"] +native = ["reqwest/native-tls"] diff --git a/algonaut_indexer/README.md b/algonaut_indexer/README.md new file mode 100644 index 00000000..9978d7e2 --- /dev/null +++ b/algonaut_indexer/README.md @@ -0,0 +1,3 @@ +# algonaut_indexer + +For more information refer to [algonaut](https://crates.io/crates/algonaut) crate. diff --git a/algonaut_client/sample.env b/algonaut_indexer/sample.env similarity index 100% rename from algonaut_client/sample.env rename to algonaut_indexer/sample.env diff --git a/algonaut_client/src/error.rs b/algonaut_indexer/src/error.rs similarity index 100% rename from algonaut_client/src/error.rs rename to algonaut_indexer/src/error.rs diff --git a/algonaut_client/src/extensions/mod.rs b/algonaut_indexer/src/extensions/mod.rs similarity index 100% rename from algonaut_client/src/extensions/mod.rs rename to algonaut_indexer/src/extensions/mod.rs diff --git a/algonaut_client/src/extensions/reqwest.rs b/algonaut_indexer/src/extensions/reqwest.rs similarity index 100% rename from algonaut_client/src/extensions/reqwest.rs rename to algonaut_indexer/src/extensions/reqwest.rs diff --git a/algonaut_client/src/algod/mod.rs b/algonaut_indexer/src/indexer/mod.rs similarity index 100% rename from algonaut_client/src/algod/mod.rs rename to algonaut_indexer/src/indexer/mod.rs diff --git a/algonaut_client/src/indexer/v2/mod.rs b/algonaut_indexer/src/indexer/v2/mod.rs similarity index 100% rename from algonaut_client/src/indexer/v2/mod.rs rename to algonaut_indexer/src/indexer/v2/mod.rs diff --git a/algonaut_client/src/lib.rs b/algonaut_indexer/src/lib.rs similarity index 67% rename from algonaut_client/src/lib.rs rename to algonaut_indexer/src/lib.rs index 1bdf9731..c5489f09 100644 --- a/algonaut_client/src/lib.rs +++ b/algonaut_indexer/src/lib.rs @@ -1,13 +1,9 @@ -/// Algorand protocol daemon -pub mod algod; /// pub mod error; /// mod extensions; /// Algorand's indexer pub mod indexer; -/// Key management daemon -pub mod kmd; /// Api token management utils pub mod token; diff --git a/algonaut_client/src/token.rs b/algonaut_indexer/src/token.rs similarity index 100% rename from algonaut_client/src/token.rs rename to algonaut_indexer/src/token.rs diff --git a/algonaut_client/Cargo.toml b/algonaut_kmd/Cargo.toml similarity index 54% rename from algonaut_client/Cargo.toml rename to algonaut_kmd/Cargo.toml index 283c6fc2..4d9c6cd1 100644 --- a/algonaut_client/Cargo.toml +++ b/algonaut_kmd/Cargo.toml @@ -1,22 +1,25 @@ [package] -authors = ["Manuel Mauro ", "Ivan Schuetz ",] +authors = [ + "Manuel Mauro ", + "Ivan Schuetz ", +] description = "API clients for the Algorand blockchain." edition = "2018" keywords = ["Algorand", "sdk"] license = "MIT" -name = "algonaut_client" +name = "algonaut_kmd" repository = "https://github.com/manuelmauro/algonaut" version = "0.4.2" [dependencies] -algonaut_model = {path = "../algonaut_model", version = "0.4.2"} -algonaut_core = {path = "../algonaut_core", version = "0.4.2"} -algonaut_crypto = {path = "../algonaut_crypto", version = "0.4.2"} -algonaut_encoding = {path = "../algonaut_encoding", version = "0.4.2"} +algonaut_model = { path = "../algonaut_model", version = "0.4.2" } +algonaut_core = { path = "../algonaut_core", version = "0.4.2" } +algonaut_crypto = { path = "../algonaut_crypto", version = "0.4.2" } +algonaut_encoding = { path = "../algonaut_encoding", version = "0.4.2" } data-encoding = "2.3.1" derive_more = "0.99.13" -reqwest = {version = "0.11", features = ["json"], default-features = false} -serde = {version = "1.0", features = ["derive"]} +reqwest = { version = "0.11", features = ["json"], default-features = false } +serde = { version = "1.0", features = ["derive"] } serde_json = "1.0.40" thiserror = "1.0.23" url = "2.2.0" diff --git a/algonaut_client/README.md b/algonaut_kmd/README.md similarity index 82% rename from algonaut_client/README.md rename to algonaut_kmd/README.md index fe0bb026..42cf85a1 100644 --- a/algonaut_client/README.md +++ b/algonaut_kmd/README.md @@ -1,3 +1,3 @@ -# algonaut_client +# algonaut_kmd For more information refer to [algonaut](https://crates.io/crates/algonaut) crate. diff --git a/algonaut_kmd/sample.env b/algonaut_kmd/sample.env new file mode 100644 index 00000000..92f60524 --- /dev/null +++ b/algonaut_kmd/sample.env @@ -0,0 +1,9 @@ +# Test env variables +# Sandbox's algorand daemon +export ALGOD_URL="http://localhost:4001" +export ALGOD_TOKEN="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" +# Sandbox's key management daemon +export KMD_URL="http://localhost:4002" +export KMD_TOKEN="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" +# Indexer +export INDEXER_URL="http://localhost:8980" \ No newline at end of file diff --git a/algonaut_kmd/src/error.rs b/algonaut_kmd/src/error.rs new file mode 100644 index 00000000..b02b0ad8 --- /dev/null +++ b/algonaut_kmd/src/error.rs @@ -0,0 +1,98 @@ +use reqwest::header::{InvalidHeaderName, InvalidHeaderValue}; +use std::fmt::Debug; +use thiserror::Error; + +#[derive(Error, Debug, Clone)] +pub enum ClientError { + /// URL parse error. + #[error("Url parsing error: {0}")] + BadUrl(String), + /// Token parse error. + #[error("Token parsing error.")] + BadToken, + /// Invalid characters in headers, e.g. "\n" + /// Can only happen with custom endpoints + #[error("Header parsing error: {0}")] + BadHeader(String), + /// HTTP calls. + #[error("http error: {0}")] + Request(#[from] RequestError), + /// General text-only errors. Dedicated error variants can be created, if needed. + #[error("Msg: {0}")] + Msg(String), +} + +#[derive(Error, Debug, Clone)] +#[error("{:?}, {}", url, details)] +pub struct RequestError { + pub url: Option, + pub details: RequestErrorDetails, +} + +impl RequestError { + pub fn new(url: Option, details: RequestErrorDetails) -> RequestError { + RequestError { url, details } + } +} + +#[derive(Error, Debug, Clone)] +pub enum RequestErrorDetails { + /// Http call error with optional message (returned by remote API) + #[error("Http error: {}, {}", status, message)] + Http { status: u16, message: String }, + /// Timeout + #[error("Timeout connecting to the server.")] + Timeout, + /// Client generated errors (while e.g. building request or decoding response) + #[error("Client error: {}", description)] + Client { description: String }, +} + +impl From for ClientError { + fn from(error: url::ParseError) -> Self { + ClientError::BadUrl(error.to_string()) + } +} + +impl From for ClientError { + fn from(error: rmp_serde::decode::Error) -> Self { + ClientError::Msg(error.to_string()) + } +} + +impl From for ClientError { + fn from(error: reqwest::Error) -> Self { + let url_str = error.url().map(|u| u.to_string()); + let request_error = if let Some(status) = error.status() { + RequestError::new( + url_str, + RequestErrorDetails::Http { + status: status.as_u16(), + message: "".to_owned(), + }, + ) + } else if error.is_timeout() { + RequestError::new(url_str, RequestErrorDetails::Timeout) + } else { + RequestError::new( + url_str, + RequestErrorDetails::Client { + description: error.to_string(), + }, + ) + }; + ClientError::Request(request_error) + } +} + +impl From for ClientError { + fn from(error: InvalidHeaderName) -> Self { + ClientError::BadHeader(error.to_string()) + } +} + +impl From for ClientError { + fn from(error: InvalidHeaderValue) -> Self { + ClientError::BadHeader(error.to_string()) + } +} diff --git a/algonaut_kmd/src/extensions/mod.rs b/algonaut_kmd/src/extensions/mod.rs new file mode 100644 index 00000000..eb3fca20 --- /dev/null +++ b/algonaut_kmd/src/extensions/mod.rs @@ -0,0 +1 @@ +pub(super) mod reqwest; diff --git a/algonaut_kmd/src/extensions/reqwest.rs b/algonaut_kmd/src/extensions/reqwest.rs new file mode 100644 index 00000000..cf3d3224 --- /dev/null +++ b/algonaut_kmd/src/extensions/reqwest.rs @@ -0,0 +1,67 @@ +use std::str::FromStr; + +use crate::{ + error::{ClientError, RequestError, RequestErrorDetails}, + Headers, +}; +use async_trait::async_trait; +use reqwest::{ + header::{HeaderMap, HeaderName, HeaderValue}, + Response, +}; +use serde::Deserialize; + +// reqwest::Response has thread unsafe contents with the WASM target, +// so it's required to implement Send, which is not possible. +// Since WASM is single threaded, this can be skipped, using ?Send +// https://docs.rs/async-trait/0.1.50/async_trait/#non-threadsafe-futures +#[cfg_attr(target_arch = "wasm32", async_trait(?Send))] +// reqwest::Response is thread safe with non WASM targets +// async_trait doesn't need additional parameters. +#[cfg_attr(not(target_arch = "wasm32"), async_trait)] +pub(crate) trait ResponseExt { + /// Maps error to custom error, with a possible message returned by API. + async fn http_error_for_status(self) -> Result; +} + +#[cfg_attr(target_arch = "wasm32", async_trait(?Send))] +#[cfg_attr(not(target_arch = "wasm32"), async_trait)] +impl ResponseExt for Response { + async fn http_error_for_status(self) -> Result { + match self.error_for_status_ref() { + // The response is not an error + Ok(_) => Ok(self), + // The response is an error + Err(_) => Err(RequestError::new( + Some(self.url().to_string()), + RequestErrorDetails::Http { + status: self.status().as_u16(), + message: parse_error_message_or_empty_string(self).await, + }, + )), + } + } +} + +/// Try to retrieve error message from JSON. +/// If there's no message, return an empty string. +async fn parse_error_message_or_empty_string(response: Response) -> String { + response + .json::() + .await + .map(|p| p.message) + .unwrap_or_else(|_| "".to_owned()) +} + +#[derive(Deserialize)] +struct HttpErrorPayload { + message: String, +} + +pub fn to_header_map(headers: Headers) -> Result { + let mut map = HeaderMap::new(); + for h in &headers { + map.insert(HeaderName::from_str(h.0)?, HeaderValue::from_str(h.1)?); + } + Ok(map) +} diff --git a/algonaut_client/src/kmd/mod.rs b/algonaut_kmd/src/kmd/mod.rs similarity index 100% rename from algonaut_client/src/kmd/mod.rs rename to algonaut_kmd/src/kmd/mod.rs diff --git a/algonaut_client/src/kmd/v1/mod.rs b/algonaut_kmd/src/kmd/v1/mod.rs similarity index 100% rename from algonaut_client/src/kmd/v1/mod.rs rename to algonaut_kmd/src/kmd/v1/mod.rs diff --git a/algonaut_kmd/src/lib.rs b/algonaut_kmd/src/lib.rs new file mode 100644 index 00000000..77e859aa --- /dev/null +++ b/algonaut_kmd/src/lib.rs @@ -0,0 +1,10 @@ +/// +pub mod error; +/// +mod extensions; +/// Key management daemon +pub mod kmd; +/// Api token management utils +pub mod token; + +pub type Headers<'a> = Vec<(&'a str, &'a str)>; diff --git a/algonaut_kmd/src/token.rs b/algonaut_kmd/src/token.rs new file mode 100644 index 00000000..a688c6d5 --- /dev/null +++ b/algonaut_kmd/src/token.rs @@ -0,0 +1,24 @@ +use crate::error::ClientError; +use derive_more::Display; + +/// An API token. +#[derive(Display)] +#[display(fmt = "{}", token)] +pub struct ApiToken { + token: String, +} + +const TOKEN_LENGTH: usize = 64; + +impl ApiToken { + /// Parses a string slice representing an API token. + pub fn parse(token: &str) -> Result { + if token.len() != TOKEN_LENGTH { + return Err(ClientError::BadToken); + } + + Ok(ApiToken { + token: token.to_string(), + }) + } +} diff --git a/algonaut_model/src/algod/mod.rs b/algonaut_model/src/algod/mod.rs deleted file mode 100644 index 7083bd82..00000000 --- a/algonaut_model/src/algod/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub mod v2; diff --git a/algonaut_model/src/algod/v2/mod.rs b/algonaut_model/src/algod/v2/mod.rs deleted file mode 100644 index 65411911..00000000 --- a/algonaut_model/src/algod/v2/mod.rs +++ /dev/null @@ -1,956 +0,0 @@ -use algonaut_core::{Address, MicroAlgos, Round, ToMsgPack}; -use algonaut_crypto::{deserialize_hash, HashDigest}; -use algonaut_encoding::{deserialize_byte32_arr_opt, deserialize_bytes}; -use fmt::Debug; -use serde::{Deserialize, Deserializer, Serialize}; -use serde_with::{serde_as, DisplayFromStr}; -use std::fmt; - -use crate::transaction::ApiSignedTransaction; - -#[serde_as] -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct Account { - /// The account public key - #[serde_as(as = "DisplayFromStr")] - pub address: Address, - - /// The total number of MicroAlgos in the account - pub amount: MicroAlgos, - - /// Specifies the amount of MicroAlgos in the account, without the pending rewards. - #[serde(rename = "amount-without-pending-rewards")] - pub amount_without_pending_rewards: u64, - - /// `appl` applications local data stored in this account. - #[serde( - default, - rename = "apps-local-state", - skip_serializing_if = "Vec::is_empty" - )] - pub apps_local_state: Vec, - - /// `tsch` stores the sum of all of the local schemas and global schemas in this account. - /// - /// Note: the raw account uses StateSchema for this type. - #[serde(rename = "apps-total-schema")] - pub apps_total_schema: Option, - - /// `asset` assets held by this account. - /// Note the raw object uses map(int) -> AssetHolding for this type. - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub assets: Vec, - - /// `spend` the address against which signing should be checked. If empty, the address of the - /// current account is used. This field can be updated in any transaction by setting the - /// RekeyTo field. - #[serde(default, rename = "auth-addr")] - #[serde_as(as = "Option")] - pub auth_addr: Option
, - - /// `appp` parameters of applications created by this account including app global data. - /// - /// Note: the raw account uses map(int) -> AppParams for this type. - #[serde( - default, - rename = "created-apps", - skip_serializing_if = "Vec::is_empty" - )] - pub created_apps: Vec, - - /// `apar` parameters of assets created by this account. - /// - /// Note: the raw account uses map(int) -> Asset for this type. - #[serde( - default, - rename = "created-assets", - skip_serializing_if = "Vec::is_empty" - )] - pub created_assets: Vec, - - /// MicroAlgo balance required by the account. The requirement grows based on asset and - /// application usage. - #[serde(rename = "min-balance")] - pub min_balance: MicroAlgos, - - /// - pub participation: Option, - - /// Amount of MicroAlgos of pending rewards in this account. - #[serde(rename = "pending-rewards")] - pub pending_rewards: MicroAlgos, - - /// `ebase` used as part of the rewards computation. Only applicable to accounts which - /// are participating. - #[serde(rename = "reward-base")] - pub reward_base: Option, - - /// `ern` total rewards of MicroAlgos the account has received, including pending rewards. - pub rewards: MicroAlgos, - - /// The round for which this information is relevant. - pub round: Round, - - /// Indicates what type of signature is used by this account, must be one of: - /// * sig - /// * msig - /// * lsig - #[serde(rename = "sig-type")] - pub sig_type: Option, - - /// `onl` delegation status of the account's MicroAlgos - /// * Offline - indicates that the associated account is delegated. - /// * Online - indicates that the associated account used as part of the delegation pool. - /// * NotParticipating - indicates that the associated account is neither a delegator nor a delegate. - pub status: String, -} - -/// Signature types. -#[derive(Debug, Serialize, Deserialize, Clone)] -pub enum SignatureType { - #[serde(rename = "sig")] - Sig, - #[serde(rename = "msig")] - MultiSig, - #[serde(rename = "lsig")] - LSig, -} - -/// AccountParticipation describes the parameters used by this account in consensus protocol. -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct AccountParticipation { - /// `sel` Selection public key (if any) currently registered for this round. - /// Pattern : "^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==\|[A-Za-z0-9+/]{3}=)?$" - #[serde( - rename = "selection-participation-key", - default, - skip_serializing_if = "Vec::is_empty", - deserialize_with = "deserialize_bytes" - )] - pub selection_participation_key: Vec, - - /// `voteFst` First round for which this participation is valid. - #[serde(rename = "vote-first-valid")] - pub vote_first_valid: u64, - - /// `voteKD` Number of subkeys in each batch of participation keys. - #[serde(rename = "vote-key-dilution")] - pub vote_key_dilution: u64, - - /// `voteLst` Last round for which this participation is valid. - #[serde(rename = "vote-last-valid")] - pub vote_last_valid: u64, - - /// `vote` root participation public key (if any) currently registered for this round. - /// Pattern : "^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==\|[A-Za-z0-9+/]{3}=)?$" - #[serde( - rename = "vote-participation-key", - default, - skip_serializing_if = "Vec::is_empty", - deserialize_with = "deserialize_bytes" - )] - pub vote_participation_key: Vec, -} - -/// Application state delta. -#[serde_as] -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct AccountStateDelta { - /// Address - #[serde_as(as = "DisplayFromStr")] - pub address: Address, - - /// Delta - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub delta: Vec, -} - -/// Application index and its parameters -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct Application { - /// `appidx` application index. - pub id: u64, - - /// `appparams` application parameters. - pub params: ApplicationParams, -} - -/// Stores local state associated with an application. -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct ApplicationLocalState { - /// The application which this local state is for. - pub id: u64, - - /// `tkv` storage. - #[serde(default, rename = "key-value", skip_serializing_if = "Vec::is_empty")] - pub key_value: Vec, - - /// `hsch` schema. - #[serde(rename = "schema")] - pub schema: ApplicationStateSchema, -} - -/// Stores the global information associated with an application. -#[serde_as] -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct ApplicationParams { - /// `approv` approval program. - /// Pattern : "^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==\|[A-Za-z0-9+/]{3}=)?$" - #[serde( - rename = "approval-program", - default, - skip_serializing_if = "Vec::is_empty", - deserialize_with = "deserialize_bytes" - )] - pub approval_program: Vec, - - /// `clearp` approval program. - /// Pattern : "^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==\|[A-Za-z0-9+/]{3}=)?$" - #[serde( - rename = "clear-state-program", - default, - skip_serializing_if = "Vec::is_empty", - deserialize_with = "deserialize_bytes" - )] - pub clear_state_program: Vec, - - /// The address that created this application. This is the address where the parameters and - /// global state for this application can be found. - #[serde_as(as = "DisplayFromStr")] - pub creator: Address, - - /// `gs` global schema - #[serde( - default, - rename = "global-state", - skip_serializing_if = "Vec::is_empty" - )] - pub global_state: Vec, - - /// `lsch` global schema - #[serde(rename = "global-state-schema")] - pub global_state_schema: Option, - - /// `lsch` local schema - #[serde(rename = "local-state-schema")] - pub local_state_schema: Option, -} - -/// Specifies maximums on the number of each type that may be stored. -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct ApplicationStateSchema { - /// `nbs` num of byte slices. - #[serde(rename = "num-byte-slice")] - pub num_byte_slice: u64, - - /// `nui` num of uints. - #[serde(rename = "num-uint")] - pub num_uint: u64, -} - -/// Specifies both the unique identifier and the parameters for an asset -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct Asset { - /// unique asset identifier - pub index: u64, - - /// Params. - pub params: AssetParams, -} - -/// Describes an asset held by an account. -/// Definition: data/basics/userBalance.go : AssetHolding -#[serde_as] -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct AssetHolding { - /// `a` number of units held. - pub amount: u64, - - ///Asset ID of the holding. - #[serde(rename = "asset-id")] - pub asset_id: u64, - - /// `f` whether or not the holding is frozen. - #[serde(rename = "is-frozen")] - pub is_frozen: bool, -} - -/// AssetParams specifies the parameters for an asset. -/// `apar` when part of an AssetConfig transaction. -/// Definition: data/transactions/asset.go : AssetParams -#[serde_as] -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct AssetParams { - /// `c` Address of account used to clawback holdings of this asset. If empty, clawback is not - /// permitted. - #[serde(default)] - #[serde_as(as = "Option")] - pub clawback: Option
, - - /// The address that created this asset. This is the address where the parameters for this - /// asset can be found, and also the address where unwanted asset units can be sent in the worst - /// case. - #[serde_as(as = "DisplayFromStr")] - pub creator: Address, - - /// `dc` The number of digits to use after the decimal point when displaying this asset. - /// If 0, the asset is not divisible. If 1, the base unit of the asset is in tenths. - /// If 2, the base unit of the asset is in hundredths, and so on. This value must be - /// between 0 and 19 (inclusive). - /// Minimum value : 0 - /// Maximum value : 19 - pub decimals: u64, - - /// `df` Whether holdings of this asset are frozen by default. - #[serde(rename = "default-frozen")] - pub default_frozen: Option, - - /// `f` Address of account used to freeze holdings of this asset. If empty, freezing is not - /// permitted. - #[serde(default)] - #[serde_as(as = "Option")] - pub freeze: Option
, - - /// `m` Address of account used to manage the keys of this asset and to destroy it. - #[serde(default)] - #[serde_as(as = "Option")] - pub manager: Option
, - - /// `am` A commitment to some unspecified asset metadata. The format of this metadata is up - /// to the application. - /// Pattern : "^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==\|[A-Za-z0-9+/]{3}=)?$" - #[serde( - default, - rename = "metadata-hash", - with = "serde_bytes", - skip_serializing_if = "Option::is_none" - )] - pub metadata_hash: Option>, - - /// `an` Name of this asset, as supplied by the creator. - pub name: Option, - - /// `r` Address of account holding reserve (non-minted) units of this asset. - #[serde(default)] - #[serde_as(as = "Option")] - pub reserve: Option
, - - /// `t` The total number of units of this asset. - pub total: u64, - - /// `un` Name of a unit of this asset, as supplied by the creator. - #[serde(rename = "unit-name")] - pub unit_name: Option, - - /// `au` URL where more information about the asset can be retrieved. - pub url: Option, -} - -/// BuildVersion -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct BuildVersion { - pub branch: String, - pub build_number: u64, - pub channel: String, - pub commit_hash: String, - pub major: u64, - pub minor: u64, -} - -impl BuildVersion { - pub fn semver(&self) -> String { - format!("{}.{}.{}", self.major, self.minor, self.build_number) - } -} - -/// Request data type for dryrun endpoint. Given the Transactions and simulated ledger state -/// upload, run TEAL scripts and return debugging information. -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct DryrunRequest { - pub accounts: Vec, - - pub apps: Vec, - - /// LatestTimestamp is available to some TEAL scripts. Defaults to the latest confirmed - /// timestamp this algod is attached to. - #[serde(rename = "latest-timestamp")] - pub latest_timestamp: u64, - - /// ProtocolVersion specifies a specific version string to operate under, otherwise whatever - /// the current protocol of the network this algod is running in. - #[serde(rename = "protocol-version")] - pub protocol_version: String, - - /// Round is available to some TEAL scripts. Defaults to the current round on the network - /// this algod is attached to. - pub round: Round, - - pub sources: Vec, - - pub txns: Vec, -} - -impl ToMsgPack for DryrunRequest {} - -/// DryrunSource is TEAL source text that gets uploaded, compiled, and inserted into transactions -/// or application state. -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct DryrunSource { - #[serde(rename = "app-index")] - pub app_index: u64, - - /// FieldName is what kind of sources this is. If lsig then it goes into the - /// transactions[this.TxnIndex].LogicSig. - /// If approv or clearp it goes into the Approval Program or Clear State Program of - /// application[this.AppIndex]. - #[serde(rename = "field-name")] - pub field_name: String, - - pub source: String, - - #[serde(rename = "txn-index")] - pub txn_index: u64, -} - -/// Stores the TEAL eval step data -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct DryrunState { - /// Evaluation error if any - pub error: Option, - - /// Line number - pub line: u64, - - /// Program counter - pub pc: u64, - - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub scratch: Vec, - - pub stack: Vec, -} - -/// DryrunTxnResult contains any LogicSig or ApplicationCall program debug information -/// and state updates from a dryrun. -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct DryrunTxnResult { - #[serde( - default, - rename = "app-call-messages", - skip_serializing_if = "Vec::is_empty" - )] - pub app_call_messages: Vec, - - #[serde( - default, - rename = "app-call-trace", - skip_serializing_if = "Vec::is_empty" - )] - pub app_call_trace: Vec, - - /// Disassembled program line by line. - /// Documented as required, but for some reason the API can send null (which is unusual, normally keys with null values are omitted) - /// so it has to be marked as optional. - // pub disassembly: Option>, - #[serde( - skip_serializing_if = "Vec::is_empty", - deserialize_with = "deserialize_vec_opt_to_vec" - )] - pub disassembly: Vec, - - #[serde( - default, - rename = "global-delta", - skip_serializing_if = "Vec::is_empty" - )] - pub global_delta: Vec, - - #[serde( - default, - rename = "local-deltas", - skip_serializing_if = "Vec::is_empty" - )] - pub local_deltas: Vec, - - #[serde( - default, - rename = "logic-sig-messages", - skip_serializing_if = "Vec::is_empty" - )] - pub logic_sig_messages: Vec, - - #[serde( - default, - rename = "logic-sig-trace", - skip_serializing_if = "Vec::is_empty" - )] - pub logic_sig_trace: Vec, - - /// Logs for the application being executed by this transaction. - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub logs: Vec, -} - -fn deserialize_vec_opt_to_vec<'de, D>(deserializer: D) -> Result, D::Error> -where - D: Deserializer<'de>, -{ - let s: Option> = Deserialize::deserialize(deserializer)?; - Ok(s.unwrap_or_default()) -} - -/// DryrunResponse -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct DryrunResponse { - pub error: Option, - - /// Protocol version is the protocol version Dryrun was operated under. - #[serde(rename = "protocol-version")] - pub protocol_version: String, - - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub txns: Vec, -} - -/// An error response with optional data field. -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct ErrorResponse { - pub data: T, - pub message: String, -} - -/// Represents a TEAL value delta. -#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)] -pub struct EvalDelta { - /// `at` delta action. - pub action: u64, - - /// `bs` bytes value. - pub bytes: Option, - - /// `ui` uint value. - pub uint: Option, -} - -/// Key-value pairs for StateDelta. -#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)] -pub struct EvalDeltaKeyValue { - pub key: String, - pub value: EvalDelta, -} - -/// Represents a key-value pair in an application store. -#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)] -pub struct TealKeyValue { - pub key: String, - pub value: TealValue, -} - -/// Represents a TEAL value. -#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)] -pub struct TealValue { - /// `tb` bytes value. - #[serde( - default, - skip_serializing_if = "Vec::is_empty", - deserialize_with = "deserialize_bytes" - )] - pub bytes: Vec, - - /// `tt` value type. - #[serde(rename = "type")] - pub value_type: u64, - - /// `ui` uint value. - pub uint: u64, -} - -/// Version contains the current algod version. -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct Version { - pub build: BuildVersion, - - /// Pattern : "^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==\|[A-Za-z0-9+/]{3}=)?$" - #[serde(deserialize_with = "deserialize_hash")] - pub genesis_hash_b64: HashDigest, - - pub genesis_id: String, - - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub versions: Vec, -} - -/// Version contains the current algod version. -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct GenesisBlock { - pub addr: Option, -} - -/// A transaction. -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct Transaction { - // #[serde(rename = "txId")] - // pub tx_id: String, -} - -/// A potentially truncated list of transactions currently in the node's transaction pool. -/// You can compute whether or not the list is truncated if the number of elements in the -/// top-transactions array is fewer than total-transactions. -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct PendingTransactions { - /// An array of signed transaction objects. - #[serde(rename = "top-transactions")] - pub top_transactions: Vec, - - /// Total number of transactions in the pool. - #[serde(rename = "total-transactions")] - pub total_transactions: u64, -} - -/// A specific pending transaction. -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct PendingTransaction { - /// The application index if the transaction was found and it created an application. - #[serde(rename = "application-index")] - pub application_index: Option, - - /// The asset index if the transaction was found and it created an asset. - #[serde(rename = "asset-index")] - pub asset_index: Option, - - /// Rewards in microalgos applied to the close remainder to account. - #[serde(rename = "close-rewards")] - pub close_rewards: Option, - - /// Closing amount for the transaction. - #[serde(rename = "closing-amount")] - pub closing_amount: Option, - - /// The round where this transaction was confirmed, if present. - #[serde(rename = "confirmed-round")] - pub confirmed_round: Option, - - /// `gd` Global state key/value changes for the application being executed by this - /// transaction. - #[serde( - default, - rename = "global-state-delta", - skip_serializing_if = "Vec::is_empty" - )] - pub global_state_delta: Vec, - - /// `ld` Local state key/value changes for the application being executed by this - /// transaction. - #[serde( - default, - rename = "local-state-delta", - skip_serializing_if = "Vec::is_empty" - )] - pub local_state_delta: Vec, - - /// Indicates that the transaction was kicked out of this node's transaction pool - /// (and specifies why that happened). An empty string indicates the transaction - /// wasn't kicked out of this node's txpool due to an error. - #[serde(rename = "pool-error")] - pub pool_error: String, - - /// Rewards in microalgos applied to the receiver account. - #[serde(rename = "receiver-rewards")] - pub receiver_rewards: Option, - - /// Rewards in microalgos applied to the sender account. - #[serde(rename = "sender-rewards")] - pub sender_rewards: Option, - - /// InnerTxns inner transactions produced by application execution. - #[serde(default, rename = "inner-txns", skip_serializing_if = "Vec::is_empty")] - pub inner_txs: Vec, - - /// Logs for the application being executed by this transaction. - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub logs: Vec, - - /// The raw signed transaction. - pub txn: Transaction, -} - -/// Information about the status of a node -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct NodeStatus { - /// The current catchpoint that is being caught up to - pub catchpoint: Option, - - /// The number of blocks that have already been obtained by the node as part of the catchup - #[serde(rename = "catchpoint-acquired-blocks")] - pub catchpoint_acquired_blocks: Option, - - /// The number of accounts from the current catchpoint that have been processed so far as - /// part of the catchup - #[serde(rename = "catchpoint-processed-accounts")] - pub catchpoint_processed_accounts: Option, - - /// The total number of accounts included in the current catchpoint - #[serde(rename = "catchpoint-total-accounts")] - pub catchpoint_total_accounts: Option, - - /// The total number of blocks that are required to complete the current catchpoint catchup - #[serde(rename = "catchpoint-total-blocks")] - pub catchpoint_total_blocks: Option, - - /// The number of accounts from the current catchpoint that have been verified so far as part - /// of the catchup - #[serde(rename = "catchpoint-verified-accounts")] - pub catchpoint_verified_accounts: Option, - - /// CatchupTime in nanoseconds - #[serde(rename = "catchup-time")] - pub catchup_time: u64, - - /// The last catchpoint seen by the node - #[serde(rename = "last-catchpoint")] - pub last_catchpoint: Option, - - /// LastRound indicates the last round seen. - #[serde(rename = "last-round")] - pub last_round: u64, - - /// LastVersion indicates the last consensus version supported. - #[serde(rename = "last-version")] - pub last_version: String, - - /// NextVersion of consensus protocol to use. - #[serde(rename = "next-version")] - pub next_version: String, - - /// NextVersionRound is the round at which the next consensus version will apply - #[serde(rename = "next-version-round")] - pub next_version_round: u64, - - /// NextVersionSupported indicates whether the next consensus version is supported by this node - #[serde(rename = "next-version-supported")] - pub next_version_supported: bool, - - /// StoppedAtUnsupportedRound indicates that the node does not support the new rounds and has - /// stopped making progress. - #[serde(rename = "stopped-at-unsupported-round")] - pub stopped_at_unsupported_round: bool, - - /// TimeSinceLastRound in nanoseconds. - #[serde(rename = "time-since-last-round")] - pub time_since_last_round: u64, -} - -/// Block -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct Block { - /// Block header data. - pub block: BlockHeader, -} - -/// Block with certificate -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct BlockWithCertificate { - /// Block header data - pub block: BlockHeaderMsgPack, - /// Certificate - pub cert: BlockCertificate, -} - -impl BlockWithCertificate { - pub fn hash(&self) -> HashDigest { - self.cert.prop.hash - } -} - -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct BlockCertificate { - pub prop: BlockCertificateProp, -} - -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct BlockCertificateProp { - #[serde(rename = "dig")] - pub hash: HashDigest, -} - -/// BlockHeader -/// -/// Note: fields seem to be managed as untyped map and currently not documented ([docs](https://developer.algorand.org/docs/rest-apis/algod/v2/#getblock-response-200)), -/// so everything optional. Some may be outdated or missing. -/// -/// For now, also, byte array representations as strings, -/// different encodings and prefixes are used, hindering a standarized deserialization. -/// -/// It probably makes sense to deserialize this and [BlockHeaderMsgPack] -/// to the same struct, but above makes it currently not possible. -/// -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct BlockHeader { - #[serde(default)] - pub earn: Option, - #[serde(default)] - pub fees: Option, - #[serde(default)] - pub frac: Option, - #[serde(default)] - pub gen: Option, - #[serde(default)] - pub gh: Option, - #[serde(default)] - pub prev: Option, - #[serde(default)] - pub proto: Option, - #[serde(default)] - pub rate: Option, - #[serde(default)] - pub rnd: Option, - #[serde(default)] - pub rwcalr: Option, - #[serde(default)] - pub rwd: Option, - #[serde(default)] - pub seed: Option, - #[serde(default)] - pub ts: Option, - #[serde(default)] - pub txn256: Option, -} - -/// BlockHeader -/// -/// Deserialized from MessagePack format -/// -/// Same underlaying content (byte arrays) as [BlockHeader] -/// See [BlockHeader] documentation for more details. -/// -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct BlockHeaderMsgPack { - #[serde(default)] - pub earn: Option, - #[serde(default, deserialize_with = "deserialize_byte32_arr_opt")] - pub fees: Option<[u8; 32]>, - #[serde(default)] - pub frac: Option, - #[serde(default)] - pub gen: Option, - #[serde(default)] - pub gh: Option, - #[serde(default)] - pub prev: Option, - #[serde(default)] - pub proto: Option, - #[serde(default)] - pub rate: Option, - #[serde(default)] - pub rnd: Option, - #[serde(default)] - pub rwcalr: Option, - #[serde(default, deserialize_with = "deserialize_byte32_arr_opt")] - pub rwd: Option<[u8; 32]>, - #[serde(default, deserialize_with = "deserialize_byte32_arr_opt")] - pub seed: Option<[u8; 32]>, - #[serde(default)] - pub ts: Option, - #[serde(default, deserialize_with = "deserialize_byte32_arr_opt")] - pub txn256: Option<[u8; 32]>, -} - -/// Catchup -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct Catchup { - /// Catchup start response string. - #[serde(rename = "catchup-message")] - pub catchup_message: String, -} - -/// Supply reported by the ledger. -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct Supply { - /// Current round - pub current_round: Round, - - /// Online money. - #[serde(rename = "online-money")] - pub online_money: u64, - - /// Total money. - #[serde(rename = "total-money")] - pub total_money: u64, -} - -/// -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct KeyRegistration { - /// The fee to use when submitting key registration transactions. Defaults to the suggested fee. - #[serde(rename = "fee")] - pub fee: Option, - - /// Value to use for two-level participation key. - #[serde(rename = "key-dilution")] - pub key_dilution: Option, - - /// Don't wait for transaction to commit before returning response. - #[serde(rename = "no-wait")] - pub no_wait: Option, - - /// The last round for which the generated participation keys will be valid. - #[serde(rename = "round-last-valid")] - pub round_last_valid: Option, -} - -/// TEAL source code. -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct SourceTeal { - /// Source code. - pub source: String, -} - -/// Compiled TEAL program. -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct ApiCompiledTeal { - /// base32 SHA512_256 of program bytes (Address style) - pub hash: String, - - /// base64 encoded program bytes. - pub result: String, -} - -/// TransactionParams contains the parameters that help a client construct a new transaction. -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct TransactionParams { - // ConsensusVersion indicates the consensus protocol version - // as of LastRound. - #[serde(rename = "consensus-version")] - pub consensus_version: String, - - /// Fee is the suggested transaction fee. - /// Fee is in units of micro-Algos per byte. - /// Fee may fall to zero but transactions must still have a fee of - /// at least MinTxnFee for the current network protocol. - #[serde(rename = "fee")] - pub fee_per_byte: MicroAlgos, - - /// GenesisHash is the hash of the genesis block. - // Pattern : "^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==\|[A-Za-z0-9+/]{3}=)?$" - #[serde(rename = "genesis-hash", deserialize_with = "deserialize_hash")] - pub genesis_hash: HashDigest, - - /// GenesisID is an ID listed in the genesis block. - #[serde(rename = "genesis-id")] - pub genesis_id: String, - - // LastRound indicates the last round seen - #[serde(rename = "last-round")] - pub last_round: Round, - - /// The minimum transaction fee (not per byte) required for the - /// txn to validate for the current network protocol. - #[serde(rename = "min-fee")] - pub min_fee: MicroAlgos, -} - -#[derive(Debug, Serialize, Deserialize, Clone)] -pub struct TransactionResponse { - #[serde(rename = "txId")] - pub tx_id: String, -} diff --git a/algonaut_model/src/lib.rs b/algonaut_model/src/lib.rs index 2dd44df4..39b88515 100644 --- a/algonaut_model/src/lib.rs +++ b/algonaut_model/src/lib.rs @@ -1,4 +1,3 @@ -pub mod algod; pub mod indexer; pub mod kmd; pub mod transaction; diff --git a/algonaut_model/src/transaction.rs b/algonaut_model/src/transaction.rs index f40ebb06..f0a5da1a 100644 --- a/algonaut_model/src/transaction.rs +++ b/algonaut_model/src/transaction.rs @@ -17,7 +17,7 @@ use std::collections::HashMap; /// /// We intentionally don't use `skip_serializing_if` for values other than `Option` for a consistent representation of optionals. /// -#[derive(Debug, Serialize, Deserialize, Clone)] +#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)] pub struct ApiTransaction { #[serde(rename = "aamt", skip_serializing_if = "Option::is_none")] pub asset_amount: Option, @@ -182,7 +182,7 @@ pub struct ApiSignedLogic { pub sig: Option, } -#[derive(Debug, Serialize, Deserialize, Clone)] +#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)] pub struct ApiSignedTransaction { #[serde(rename = "lsig", skip_serializing_if = "Option::is_none")] pub lsig: Option, diff --git a/algonaut_transaction/Cargo.toml b/algonaut_transaction/Cargo.toml index 7c1db998..1c6aeddb 100644 --- a/algonaut_transaction/Cargo.toml +++ b/algonaut_transaction/Cargo.toml @@ -1,5 +1,8 @@ [package] -authors = ["Manuel Mauro ", "Ivan Schuetz ",] +authors = [ + "Manuel Mauro ", + "Ivan Schuetz ", +] description = "Implementation of the Algorand blockchain transaction set." edition = "2018" keywords = ["Algorand", "sdk"] @@ -9,18 +12,19 @@ repository = "https://github.com/manuelmauro/algonaut" version = "0.4.2" [dependencies] -algonaut_core = {path = "../algonaut_core", version = "0.4.2"} -algonaut_crypto = {path = "../algonaut_crypto", version = "0.4.2"} -algonaut_encoding = {path = "../algonaut_encoding", version = "0.4.2"} -algonaut_model = {path = "../algonaut_model", version = "0.4.2"} -algonaut_abi = {path = "../algonaut_abi", version = "0.4.2"} +algonaut_algod = { path = "../algonaut_algod", version = "0.4.2" } +algonaut_core = { path = "../algonaut_core", version = "0.4.2" } +algonaut_crypto = { path = "../algonaut_crypto", version = "0.4.2" } +algonaut_encoding = { path = "../algonaut_encoding", version = "0.4.2" } +algonaut_model = { path = "../algonaut_model", version = "0.4.2" } +algonaut_abi = { path = "../algonaut_abi", version = "0.4.2" } data-encoding = "2.3.1" derive_more = "0.99.13" rand = "0.8.3" getrandom = { version = "0.2.2", features = ["js"] } ring = "0.16.19" rmp-serde = "1.0.0" -serde = {version = "1.0", features = ["derive"]} +serde = { version = "1.0", features = ["derive"] } serde_bytes = "0.11.4" sha2 = "0.10.1" thiserror = "1.0.23" diff --git a/algonaut_transaction/src/builder.rs b/algonaut_transaction/src/builder.rs index 5d976b91..56e25984 100644 --- a/algonaut_transaction/src/builder.rs +++ b/algonaut_transaction/src/builder.rs @@ -7,32 +7,13 @@ use crate::{ TransactionType, }, }; -use algonaut_core::{ - Address, CompiledTeal, MicroAlgos, Round, SuggestedTransactionParams, VotePk, VrfPk, -}; +use algonaut_algod::models::TransactionParams200Response; +use algonaut_core::{Address, CompiledTeal, MicroAlgos, Round, VotePk, VrfPk}; use algonaut_crypto::HashDigest; -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum TxnFee { - /// The fee is calculated based on the estimated signed tx size, fee per byte and a min fee - Estimated { - fee_per_byte: MicroAlgos, - min_fee: MicroAlgos, - }, - /// Set directly the fee - Fixed(MicroAlgos), -} - -impl TxnFee { - /// Useful in group txs, when fees are paid by other txn - pub fn zero() -> TxnFee { - TxnFee::Fixed(MicroAlgos(0)) - } -} - /// A builder for [Transaction]. pub struct TxnBuilder { - fee: TxnFee, + fee: MicroAlgos, first_valid: Round, genesis_hash: HashDigest, last_valid: Round, @@ -48,29 +29,22 @@ impl TxnBuilder { /// Convenience to initialize builder with suggested transaction params /// /// The txn fee is estimated, based on params. To set the fee manually, use [with_fee](Self::with_fee) or [new](Self::new). - pub fn with(params: &SuggestedTransactionParams, txn_type: TransactionType) -> Self { - Self::with_fee( - params, - TxnFee::Estimated { - fee_per_byte: params.fee_per_byte, - min_fee: params.min_fee, - }, - txn_type, - ) + pub fn with(params: &TransactionParams200Response, txn_type: TransactionType) -> Self { + Self::with_fee(params, MicroAlgos(params.min_fee), txn_type) } /// Convenience to initialize builder with suggested transaction params, and set the fee manually (ignoring the fee fields in params). /// /// Useful e.g. in txns groups where one txn pays the fee for others. pub fn with_fee( - params: &SuggestedTransactionParams, - fee: TxnFee, + params: &TransactionParams200Response, + fee: MicroAlgos, txn_type: TransactionType, ) -> Self { Self::new( fee, - params.first_valid, - params.last_valid, + Round(params.last_round), + Round(params.last_round + 1000), params.genesis_hash, txn_type, ) @@ -78,7 +52,7 @@ impl TxnBuilder { } pub fn new( - fee: TxnFee, + fee: MicroAlgos, first_valid: Round, last_valid: Round, genesis_hash: HashDigest, @@ -124,23 +98,7 @@ impl TxnBuilder { } pub fn build(self) -> Result { - Ok(match self.fee { - TxnFee::Estimated { - fee_per_byte, - min_fee, - } => self.build_tx_with_calculated_basic_sig_fee(fee_per_byte, min_fee)?, - TxnFee::Fixed(fee) => self.build_tx(fee), - }) - } - - fn build_tx_with_calculated_basic_sig_fee( - &self, - fee_per_byte: MicroAlgos, - min_fee: MicroAlgos, - ) -> Result { - let mut txn = self.build_tx(MicroAlgos(0)); - txn.fee = txn.estimate_basic_sig_fee(fee_per_byte, min_fee)?; - Ok(txn) + Ok(self.build_tx(self.fee)) } fn build_tx(&self, fee: MicroAlgos) -> Transaction { diff --git a/algonaut_transaction/src/transaction.rs b/algonaut_transaction/src/transaction.rs index 7568f57c..0868e841 100644 --- a/algonaut_transaction/src/transaction.rs +++ b/algonaut_transaction/src/transaction.rs @@ -21,7 +21,7 @@ use std::fmt::Debug; use std::fmt::Formatter; /// Enum containing the types of transactions and their specific fields -#[derive(Debug, Clone, Eq, PartialEq)] +#[derive(Debug, Clone, PartialEq)] pub enum TransactionType { Payment(Payment), KeyRegistration(KeyRegistration), @@ -35,7 +35,7 @@ pub enum TransactionType { } /// A transaction that can appear in a block -#[derive(Debug, Clone, Eq, PartialEq)] +#[derive(Debug, Clone, PartialEq)] pub struct Transaction { /// Paid by the sender to the FeeSink to prevent denial-of-service. The minimum fee on Algorand /// is currently 1000 microAlgos. @@ -325,7 +325,7 @@ pub struct AssetFreezeTransaction { } /// -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, PartialEq)] pub struct ApplicationCallTransaction { /// The address of the account that signs and pays the fee. pub sender: Address, @@ -416,7 +416,7 @@ pub struct StateSchema { /// Wraps a transaction in a signature. The encoding of this struct is suitable to be broadcast /// on the network -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, PartialEq)] pub struct SignedTransaction { pub transaction: Transaction, pub transaction_id: String, diff --git a/examples/algod_client.rs b/examples/algod_client.rs index 4f0231d8..04625074 100644 --- a/examples/algod_client.rs +++ b/examples/algod_client.rs @@ -1,5 +1,4 @@ use algonaut::algod::v2::Algod; -use algonaut::core::Round; use dotenv::dotenv; use std::env; use std::error::Error; @@ -26,7 +25,7 @@ async fn main() -> Result<(), Box> { info!("algod latest version: {}", node_status.last_version); // fetch block information - let last_block = algod.block(Round(node_status.last_round)).await?; + let last_block = algod.block(node_status.last_round).await?; info!("{:?}", last_block); Ok(()) diff --git a/examples/app_call.rs b/examples/app_call.rs index ee6d57c7..0f89e6d0 100644 --- a/examples/app_call.rs +++ b/examples/app_call.rs @@ -20,12 +20,13 @@ async fn main() -> Result<(), Box> { let alice = Account::from_mnemonic(&env::var("ALICE_MNEMONIC")?)?; info!("retrieving suggested params"); - let params = algod.suggested_transaction_params().await?; + let params = algod.txn_params().await?; info!("building transaction"); let t = TxnBuilder::with( ¶ms, - CallApplication::new(alice.address(), 3) + // TODO set a correct app-id here + CallApplication::new(alice.address(), 5) .app_arguments(vec![vec![1, 0], vec![255]]) .build(), ) @@ -35,7 +36,7 @@ async fn main() -> Result<(), Box> { let signed_t = alice.sign_transaction(t)?; info!("broadcasting transaction"); - let send_response = algod.broadcast_signed_transaction(&signed_t).await?; + let send_response = algod.send_txn(&signed_t).await?; info!("response: {:?}", send_response); Ok(()) diff --git a/examples/app_clear_state.rs b/examples/app_clear_state.rs index ad4f0211..eebf317d 100644 --- a/examples/app_clear_state.rs +++ b/examples/app_clear_state.rs @@ -20,17 +20,19 @@ async fn main() -> Result<(), Box> { let alice = Account::from_mnemonic(&env::var("ALICE_MNEMONIC")?)?; info!("retrieving suggested params"); - let params = algod.suggested_transaction_params().await?; + let params = algod.txn_params().await?; info!("building CreateApplication transaction"); // to test this, create an application that sets local state and opt-in, for/with the account sending this transaction. - let t = TxnBuilder::with(¶ms, ClearApplication::new(alice.address(), 3).build()).build()?; + // TODO set a correct app-id here + let t = + TxnBuilder::with(¶ms, ClearApplication::new(alice.address(), 11).build()).build()?; info!("signing transaction"); let signed_t = alice.sign_transaction(t)?; info!("broadcasting transaction"); - let send_response = algod.broadcast_signed_transaction(&signed_t).await?; + let send_response = algod.send_txn(&signed_t).await?; info!("response: {:?}", send_response); Ok(()) diff --git a/examples/app_close_out.rs b/examples/app_close_out.rs index 098c73d7..97fd134f 100644 --- a/examples/app_close_out.rs +++ b/examples/app_close_out.rs @@ -20,18 +20,19 @@ async fn main() -> Result<(), Box> { let alice = Account::from_mnemonic(&env::var("ALICE_MNEMONIC")?)?; info!("retrieving suggested params"); - let params = algod.suggested_transaction_params().await?; + let params = algod.txn_params().await?; info!("building CloseApplication transaction"); // to test this, create an application that sets local state and opt-in, for/with the account sending this transaction. // the approval program has to return success for the local state to be cleared. - let t = TxnBuilder::with(¶ms, CloseApplication::new(alice.address(), 3).build()).build()?; + // TODO set a correct app-id here + let t = TxnBuilder::with(¶ms, CloseApplication::new(alice.address(), 0).build()).build()?; info!("signing transaction"); let signed_t = alice.sign_transaction(t)?; info!("broadcasting transaction"); - let send_response = algod.broadcast_signed_transaction(&signed_t).await?; + let send_response = algod.send_txn(&signed_t).await?; info!("response: {:?}", send_response); Ok(()) diff --git a/examples/app_create.rs b/examples/app_create.rs index 4aac4c82..f356c319 100644 --- a/examples/app_create.rs +++ b/examples/app_create.rs @@ -1,10 +1,9 @@ use algonaut::algod::v2::Algod; -use algonaut::error::ServiceError; -use algonaut::model::algod::v2::PendingTransaction; use algonaut::transaction::account::Account; use algonaut::transaction::transaction::StateSchema; use algonaut::transaction::CreateApplication; use algonaut::transaction::TxnBuilder; +use algonaut_algod::models::PendingTransactionResponse; use dotenv::dotenv; use std::env; use std::error::Error; @@ -42,19 +41,19 @@ int 1 "# .as_bytes(); - info!("compiling approva and clear programs"); - let compiled_approval_program = algod.compile_teal(&approval_program).await?; - let compiled_clear_program = algod.compile_teal(&clear_program).await?; + info!("compiling approval and clear programs"); + let compiled_approval_program = algod.teal_compile(approval_program, None).await?; + let compiled_clear_program = algod.teal_compile(clear_program, None).await?; info!("retrieving suggested params"); - let params = algod.suggested_transaction_params().await?; + let params = algod.txn_params().await?; info!("building CreateApplication transaction"); let t = TxnBuilder::with( ¶ms, CreateApplication::new( alice.address(), - compiled_approval_program.clone(), + compiled_approval_program, compiled_clear_program, StateSchema { number_ints: 0, @@ -74,7 +73,7 @@ int 1 let signed_t = alice.sign_transaction(t)?; info!("broadcasting transaction"); - let send_response = algod.broadcast_signed_transaction(&signed_t).await?; + let send_response = algod.send_txn(&signed_t).await?; info!("waiting for transaction finality"); let pending_t = wait_for_pending_transaction(&algod, &send_response.tx_id).await?; @@ -91,11 +90,11 @@ int 1 async fn wait_for_pending_transaction( algod: &Algod, txid: &str, -) -> Result, ServiceError> { +) -> Result, algonaut::Error> { let timeout = Duration::from_secs(10); let start = Instant::now(); loop { - let pending_transaction = algod.pending_transaction_with_id(txid).await?; + let pending_transaction = algod.pending_txn(txid).await?; // If the transaction has been confirmed or we time out, exit. if pending_transaction.confirmed_round.is_some() { return Ok(Some(pending_transaction)); diff --git a/examples/app_delete.rs b/examples/app_delete.rs index ba8a663d..170fda33 100644 --- a/examples/app_delete.rs +++ b/examples/app_delete.rs @@ -20,7 +20,7 @@ async fn main() -> Result<(), Box> { let alice = Account::from_mnemonic(&env::var("ALICE_MNEMONIC")?)?; info!("retrieving suggested params"); - let params = algod.suggested_transaction_params().await?; + let params = algod.txn_params().await?; info!("building DeleteApplication transaction"); let t = TxnBuilder::with( @@ -35,7 +35,7 @@ async fn main() -> Result<(), Box> { let signed_t = alice.sign_transaction(t)?; info!("broadcasting transaction"); - let send_response = algod.broadcast_signed_transaction(&signed_t).await?; + let send_response = algod.send_txn(&signed_t).await?; info!("response: {:?}", send_response); Ok(()) diff --git a/examples/app_optin.rs b/examples/app_optin.rs index d95eb816..3e26a838 100644 --- a/examples/app_optin.rs +++ b/examples/app_optin.rs @@ -20,12 +20,13 @@ async fn main() -> Result<(), Box> { let alice = Account::from_mnemonic(&env::var("ALICE_MNEMONIC")?)?; info!("retrieving suggested params"); - let params = algod.suggested_transaction_params().await?; + let params = algod.txn_params().await?; info!("building OptInApplication transaction"); let t = TxnBuilder::with( ¶ms, - OptInApplication::new(alice.address(), 3) + // TODO set a correct app-id here + OptInApplication::new(alice.address(), 11) .app_arguments(vec![vec![1, 0], vec![255]]) .build(), ) @@ -35,7 +36,7 @@ async fn main() -> Result<(), Box> { let signed_t = alice.sign_transaction(t)?; info!("broadcasting transaction"); - let send_response = algod.broadcast_signed_transaction(&signed_t).await?; + let send_response = algod.send_txn(&signed_t).await?; info!("response: {:?}", send_response); Ok(()) diff --git a/examples/app_update.rs b/examples/app_update.rs index a4f5068d..35c0a3ec 100644 --- a/examples/app_update.rs +++ b/examples/app_update.rs @@ -34,13 +34,13 @@ int 1 .as_bytes(); info!("compiling approval program"); - let compiled_approval_program = algod.compile_teal(&approval_program).await?; + let compiled_approval_program = algod.teal_compile(approval_program, None).await?; info!("compiling approval program"); - let compiled_clear_program = algod.compile_teal(&clear_program).await?; + let compiled_clear_program = algod.teal_compile(clear_program, None).await?; info!("retrieving suggested params"); - let params = algod.suggested_transaction_params().await?; + let params = algod.txn_params().await?; info!("building UpdateApplication transaction"); let t = TxnBuilder::with( @@ -60,7 +60,7 @@ int 1 let signed_t = alice.sign_transaction(t)?; info!("broadcasting transaction"); - let send_response = algod.broadcast_signed_transaction(&signed_t).await?; + let send_response = algod.send_txn(&signed_t).await?; info!("response: {:?}", send_response); Ok(()) diff --git a/examples/asset_clawback.rs b/examples/asset_clawback.rs index fe166d0d..45d4887d 100644 --- a/examples/asset_clawback.rs +++ b/examples/asset_clawback.rs @@ -24,7 +24,7 @@ async fn main() -> Result<(), Box> { let bob = Account::from_mnemonic(&env::var("BOB_MNEMONIC")?)?; info!("retrieving suggested params"); - let params = algod.suggested_transaction_params().await?; + let params = algod.txn_params().await?; info!("building ClawbackAsset transaction"); let t = TxnBuilder::with( @@ -39,7 +39,7 @@ async fn main() -> Result<(), Box> { info!("broadcasting transaction"); // Broadcast the transaction to the network // Note this transaction will get rejected because the accounts do not have any tokens - let send_response = algod.broadcast_signed_transaction(&signed_t).await; + let send_response = algod.send_txn(&signed_t).await; info!("response: {:?}", send_response); Ok(()) diff --git a/examples/asset_create.rs b/examples/asset_create.rs index 0e0527f9..3a5466c6 100644 --- a/examples/asset_create.rs +++ b/examples/asset_create.rs @@ -1,6 +1,5 @@ use algonaut::algod::v2::Algod; -use algonaut::error::ServiceError; -use algonaut::model::algod::v2::PendingTransaction; +use algonaut::openapi_algod::models::PendingTransactionResponse; use algonaut::transaction::account::Account; use algonaut::transaction::{CreateAsset, TxnBuilder}; use dotenv::dotenv; @@ -25,7 +24,7 @@ async fn main() -> Result<(), Box> { info!("creator: {:?}", alice.address()); info!("retrieving suggested params"); - let params = algod.suggested_transaction_params().await?; + let params = algod.txn_params().await?; info!("building CreateAsset transaction"); let t = TxnBuilder::with( @@ -48,7 +47,7 @@ async fn main() -> Result<(), Box> { info!("broadcasting transaction"); // broadcast the transaction to the network - let send_response = algod.broadcast_signed_transaction(&signed_t).await?; + let send_response = algod.send_txn(&signed_t).await?; info!("transaction ID: {}", send_response.tx_id); info!("waiting for transaction finality"); @@ -62,11 +61,11 @@ async fn main() -> Result<(), Box> { async fn wait_for_pending_transaction( algod: &Algod, txid: &str, -) -> Result, ServiceError> { +) -> Result, algonaut::Error> { let timeout = Duration::from_secs(10); let start = Instant::now(); loop { - let pending_transaction = algod.pending_transaction_with_id(txid).await?; + let pending_transaction = algod.pending_txn(txid).await?; // If the transaction has been confirmed or we time out, exit. if pending_transaction.confirmed_round.is_some() { return Ok(Some(pending_transaction)); diff --git a/examples/asset_optin.rs b/examples/asset_optin.rs index 245d959d..f4014f5f 100644 --- a/examples/asset_optin.rs +++ b/examples/asset_optin.rs @@ -20,10 +20,10 @@ async fn main() -> Result<(), Box> { info!("bob's address {:?}", bob.address()); info!("retrieving suggested params"); - let params = algod.suggested_transaction_params().await?; + let params = algod.txn_params().await?; info!("building AcceptAsset transaction"); - let t = TxnBuilder::with(¶ms, AcceptAsset::new(bob.address(), 21).build()).build()?; + let t = TxnBuilder::with(¶ms, AcceptAsset::new(bob.address(), 16).build()).build()?; info!("signing transaction"); let sign_response = bob.sign_transaction(t)?; @@ -31,7 +31,7 @@ async fn main() -> Result<(), Box> { info!("broadcasting transaction"); // Broadcast the transaction to the network // Note this transaction will get rejected because the accounts do not have any tokens - let send_response = algod.broadcast_signed_transaction(&sign_response).await; + let send_response = algod.send_txn(&sign_response).await; info!("response: {:?}", send_response); Ok(()) diff --git a/examples/asset_transfer.rs b/examples/asset_transfer.rs index 027e10ec..a398c3c6 100644 --- a/examples/asset_transfer.rs +++ b/examples/asset_transfer.rs @@ -20,12 +20,12 @@ async fn main() -> Result<(), Box> { let bob = Account::from_mnemonic(&env::var("BOB_MNEMONIC")?)?; info!("retrieving suggested params"); - let params = algod.suggested_transaction_params().await?; + let params = algod.txn_params().await?; info!("building TransferAsset transaction"); let t = TxnBuilder::with( ¶ms, - TransferAsset::new(alice.address(), 21, 1, bob.address()).build(), + TransferAsset::new(alice.address(), 16, 1, bob.address()).build(), ) .build()?; @@ -35,7 +35,7 @@ async fn main() -> Result<(), Box> { info!("broadcasting transaction"); // Broadcast the transaction to the network // Note this transaction will get rejected because the accounts do not have any tokens - let send_response = algod.broadcast_signed_transaction(&sign_response).await; + let send_response = algod.send_txn(&sign_response).await; info!("response: {:?}", send_response); Ok(()) diff --git a/examples/atomic_swap.rs b/examples/atomic_swap.rs index be9c9683..5304a600 100644 --- a/examples/atomic_swap.rs +++ b/examples/atomic_swap.rs @@ -23,7 +23,7 @@ async fn main() -> Result<(), Box> { let bob = Account::from_mnemonic(&env::var("BOB_MNEMONIC")?)?; info!("retrieving suggested params"); - let params = algod.suggested_transaction_params().await?; + let params = algod.txn_params().await?; // To keep the example short and as self-contained as possible, both transactions send Algos. // Normally you'll want to submit e.g. a payment and asset transfer or asset transfers for different assets. @@ -50,9 +50,7 @@ async fn main() -> Result<(), Box> { let signed_t2 = bob.sign_transaction(t2)?; info!("broadcasting transaction"); - let send_response = algod - .broadcast_signed_transactions(&[signed_t1, signed_t2]) - .await; + let send_response = algod.send_txns(&[signed_t1, signed_t2]).await; info!("response: {:?}", send_response); Ok(()) diff --git a/examples/key_reg.rs b/examples/key_reg.rs index 8b212cd2..b9ea4e2a 100644 --- a/examples/key_reg.rs +++ b/examples/key_reg.rs @@ -1,5 +1,5 @@ use algonaut::algod::v2::Algod; -use algonaut::core::{VotePk, VrfPk}; +use algonaut::core::{Round, VotePk, VrfPk}; use algonaut::transaction::RegisterKey; use algonaut::transaction::{account::Account, TxnBuilder}; use dotenv::dotenv; @@ -23,7 +23,7 @@ async fn main() -> Result<(), Box> { let selection_pk_str = "A3s+2bgKlbG9qIaA4wJsrrJl8mVKGzTp/h6gGEyZmAg="; info!("retrieving suggested params"); - let params = algod.suggested_transaction_params().await?; + let params = algod.txn_params().await?; info!("building RegisterKey transaction"); let t = TxnBuilder::with( @@ -32,8 +32,8 @@ async fn main() -> Result<(), Box> { alice.address(), VotePk::from_base64_str(vote_pk_str)?, VrfPk::from_base64_str(selection_pk_str)?, - params.first_valid, - params.first_valid + 3_000_000, + Round(params.last_round), + Round(params.last_round + 3_000_000), 10_000, ) .build(), @@ -46,7 +46,7 @@ async fn main() -> Result<(), Box> { info!("broadcasting transaction"); // Broadcast the transaction to the network // Note this transaction will get rejected because the accounts do not have any tokens - let send_response = algod.broadcast_signed_transaction(&sign_response).await; + let send_response = algod.send_txn(&sign_response).await; info!("{:?}", send_response); Ok(()) diff --git a/examples/kmd_sign_submit_transaction.rs b/examples/kmd_sign_submit_transaction.rs index acab6103..939c2371 100644 --- a/examples/kmd_sign_submit_transaction.rs +++ b/examples/kmd_sign_submit_transaction.rs @@ -36,7 +36,7 @@ async fn main() -> Result<(), Box> { info!("retrieving account for sender"); // an account with some funds in our sandbox - let sender = "ADD HERE AN ALGO ADDRESS FROM YOUR kmd/sandbox" + let sender = "OV4BQOSU7RQODSJ3VK4EXL3JOKZFO3IT3EKWVHHPQBEJOXEVNOJT545BLU" .parse() .expect("You need to specify an Algorand address from your kmd instance"); println!("sender: {:?}", sender); @@ -50,7 +50,7 @@ async fn main() -> Result<(), Box> { let algod = Algod::new(&env::var("ALGOD_URL")?, &env::var("ALGOD_TOKEN")?)?; info!("retrieving suggested params"); - let params = algod.suggested_transaction_params().await?; + let params = algod.txn_params().await?; info!("building Pay transaction"); let t = @@ -63,7 +63,7 @@ async fn main() -> Result<(), Box> { info!("broadcasting transaction"); // broadcast the transaction to the network let send_response = algod - .broadcast_raw_transaction(&sign_response.signed_transaction) + .send_raw_txn(&sign_response.signed_transaction) .await?; info!("transaction ID: {}", send_response.tx_id); diff --git a/examples/logic_sig_contract_account.rs b/examples/logic_sig_contract_account.rs index 702a1eaf..220c1de6 100644 --- a/examples/logic_sig_contract_account.rs +++ b/examples/logic_sig_contract_account.rs @@ -19,7 +19,7 @@ async fn main() -> Result<(), Box> { info!("compiling teal program"); let compiled_teal = algod - .compile_teal( + .teal_compile( r#" #pragma version 4 arg 0 @@ -31,6 +31,7 @@ byte 0xFF && "# .as_bytes(), + None, ) .await?; @@ -41,7 +42,7 @@ byte 0xFF let receiver = env::var("ALICE_ADDRESS")?.parse()?; info!("retrieving suggested params"); - let params = algod.suggested_transaction_params().await?; + let params = algod.txn_params().await?; info!("building Pay transaction"); let t = TxnBuilder::with( @@ -55,7 +56,7 @@ byte 0xFF info!("broadcasting transaction"); // the transaction will fail because contract_account has no funds - let send_response = algod.broadcast_signed_transaction(&signed_t).await; + let send_response = algod.send_txn(&signed_t).await; info!("response: {:?}", send_response); Ok(()) diff --git a/examples/logic_sig_delegated.rs b/examples/logic_sig_delegated.rs index 83d384f2..e0a6fa91 100644 --- a/examples/logic_sig_delegated.rs +++ b/examples/logic_sig_delegated.rs @@ -20,12 +20,13 @@ async fn main() -> Result<(), Box> { info!("compiling teal program"); let program = algod - .compile_teal( + .teal_compile( r#" #pragma version 3 int 1 "# .as_bytes(), + None, ) .await?; @@ -36,7 +37,7 @@ int 1 let bob = Account::from_mnemonic(&env::var("BOB_MNEMONIC")?)?; info!("retrieving suggested params"); - let params = algod.suggested_transaction_params().await?; + let params = algod.txn_params().await?; info!("building Pay transaction"); let t = TxnBuilder::with( @@ -61,7 +62,7 @@ int 1 }; info!("broadcasting transaction"); - let send_response = algod.broadcast_signed_transaction(&signed_t).await; + let send_response = algod.send_txn(&signed_t).await; info!("response: {:?}", send_response); Ok(()) diff --git a/examples/logic_sig_delegated_multi.rs b/examples/logic_sig_delegated_multi.rs index 1157f779..df90de29 100644 --- a/examples/logic_sig_delegated_multi.rs +++ b/examples/logic_sig_delegated_multi.rs @@ -20,12 +20,13 @@ async fn main() -> Result<(), Box> { info!("compiling teal program"); let program = algod - .compile_teal( + .teal_compile( r#" #pragma version 3 int 1 "# .as_bytes(), + None, ) .await?; @@ -42,7 +43,7 @@ int 1 let multisig_address = MultisigAddress::new(1, 2, &[alice.address(), bob.address()])?; info!("retrieving suggested params"); - let params = algod.suggested_transaction_params().await?; + let params = algod.txn_params().await?; info!("building Pay transaction"); let t = TxnBuilder::with( @@ -74,7 +75,7 @@ int 1 info!("broadcasting transaction"); // the transaction will fail because the multisig address has no funds - let send_response = algod.broadcast_signed_transaction(&signed_t).await; + let send_response = algod.send_txn(&signed_t).await; info!("response: {:?}", send_response); Ok(()) diff --git a/examples/multi_sig.rs b/examples/multi_sig.rs index 807b7680..591ca172 100644 --- a/examples/multi_sig.rs +++ b/examples/multi_sig.rs @@ -28,7 +28,7 @@ async fn main() -> Result<(), Box> { info!("multisig address: {}", multisig_address.address()); info!("retrieving suggested params"); - let params = algod.suggested_transaction_params().await?; + let params = algod.txn_params().await?; info!("building Pay transaction"); let t = TxnBuilder::with( @@ -61,7 +61,7 @@ async fn main() -> Result<(), Box> { info!("broadcasting transaction"); // the transaction will fail because the multisig address has no funds - let send_response = algod.broadcast_signed_transaction(&signed_t).await; + let send_response = algod.send_txn(&signed_t).await; info!("response: {:?}", send_response); Ok(()) diff --git a/examples/payment.rs b/examples/payment.rs index ce3b1dfd..de5dbee6 100644 --- a/examples/payment.rs +++ b/examples/payment.rs @@ -23,7 +23,7 @@ async fn main() -> Result<(), Box> { let bob = Account::from_mnemonic(&env::var("BOB_MNEMONIC")?)?; info!("retrieving suggested params"); - let params = algod.suggested_transaction_params().await?; + let params = algod.txn_params().await?; info!("building Pay transaction"); let t = TxnBuilder::with( @@ -36,7 +36,7 @@ async fn main() -> Result<(), Box> { let sign_response = alice.sign_transaction(t)?; info!("broadcasting transaction"); - let send_response = algod.broadcast_signed_transaction(&sign_response).await; + let send_response = algod.send_txn(&sign_response).await; info!("response: {:?}", send_response); Ok(()) diff --git a/examples/quickstart.rs b/examples/quickstart.rs index 58b7fca3..b9a4b9dc 100644 --- a/examples/quickstart.rs +++ b/examples/quickstart.rs @@ -21,7 +21,7 @@ async fn main() -> Result<(), Box> { info!("creating indexer client"); let indexer = Indexer::new(&env::var("INDEXER_URL")?)?; - info!("algod versions: {:?}", algod.versions().await?); + info!("algod versions: {:?}", algod.version().await?); info!("kmd versions: {:?}", kmd.versions().await?); info!("indexer health: {:?}", indexer.health().await); diff --git a/examples/rekey.rs b/examples/rekey.rs index ad1f9a37..68e085eb 100644 --- a/examples/rekey.rs +++ b/examples/rekey.rs @@ -27,11 +27,11 @@ async fn main() -> Result<(), Box> { info!("checking auth address"); // double check that rekeyed account's auth address is not set - let account_infos = algod.account_information(&rekeyed_acc_address).await?; + let account_infos = algod.account(&rekeyed_acc_address.to_string()).await?; assert!(account_infos.auth_addr.is_none()); info!("retrieving suggested params"); - let params = algod.suggested_transaction_params().await?; + let params = algod.txn_params().await?; info!("creating rekey-ing transaction"); // rekey @@ -46,14 +46,17 @@ async fn main() -> Result<(), Box> { let rekey_signed = rekeyed_acc.sign_transaction(rekey_tx)?; info!("broadcasting transaction"); - let rekey_response = algod.broadcast_signed_transaction(&rekey_signed).await?; + let rekey_response = algod.send_txn(&rekey_signed).await?; wait_for_pending_transaction(&algod, &rekey_response.tx_id).await?; info!("rekey success"); info!("verifying the rekey success"); // verify: rekey_to address is set as auth address of the rekeyed acc - let account_infos = algod.account_information(&rekeyed_acc_address).await?; - assert_eq!(Some(rekey_to_acc_address), account_infos.auth_addr); + let account_infos = algod.account(&rekeyed_acc_address.to_string()).await?; + assert_eq!( + Some(rekey_to_acc_address.to_string()), + account_infos.auth_addr + ); info!("testing the rekey success"); // verify: send a tx with the rekeyed address as sender, signing with rekey_to account @@ -68,7 +71,7 @@ async fn main() -> Result<(), Box> { let payment_signed = rekey_to_acc.sign_transaction(payment_tx)?; info!("broadcasting transaction"); - let payment_response = algod.broadcast_signed_transaction(&payment_signed).await; + let payment_response = algod.send_txn(&payment_signed).await; info!("payment response: {:?}", payment_response); assert!(payment_response.is_ok()); diff --git a/examples/sign_offline.rs b/examples/sign_offline.rs index 08925f19..be28219d 100644 --- a/examples/sign_offline.rs +++ b/examples/sign_offline.rs @@ -22,7 +22,7 @@ async fn main() -> Result<(), Box> { let alice = Account::from_mnemonic(&env::var("ALICE_MNEMONIC")?)?; info!("retrieving suggested params"); - let params = algod.suggested_transaction_params().await?; + let params = algod.txn_params().await?; info!("building Pay transaction"); let t = TxnBuilder::with( diff --git a/examples/submit_file.rs b/examples/submit_file.rs index cbb1af29..6155e51a 100644 --- a/examples/submit_file.rs +++ b/examples/submit_file.rs @@ -21,7 +21,7 @@ async fn main() -> Result<(), Box> { let algod = Algod::new(&env::var("ALGOD_URL")?, &env::var("ALGOD_TOKEN")?)?; info!("broadcasting transaction"); - let send_response = algod.broadcast_raw_transaction(&raw_transaction).await?; + let send_response = algod.send_raw_txn(&raw_transaction).await?; info!("transaction ID: {}", send_response.tx_id); Ok(()) diff --git a/src/algod/v2/error.rs b/src/algod/v2/error.rs new file mode 100644 index 00000000..d1e10de5 --- /dev/null +++ b/src/algod/v2/error.rs @@ -0,0 +1,17 @@ +use std::fmt::Debug; + +use algonaut_algod::apis; +use thiserror::Error; + +#[derive(Error, Debug, Clone)] +pub enum AlgodError { + /// General text-only errors. Dedicated error variants can be created, if needed. + #[error("Msg: {0}")] + Msg(String), +} + +impl From> for AlgodError { + fn from(error: apis::Error) -> Self { + AlgodError::Msg(format!("{:?}", error)) + } +} diff --git a/src/algod/v2/mod.rs b/src/algod/v2/mod.rs index 991c485e..c99391dd 100644 --- a/src/algod/v2/mod.rs +++ b/src/algod/v2/mod.rs @@ -1,18 +1,30 @@ -use algonaut_client::{algod::v2::Client, token::ApiToken, Headers}; -use algonaut_core::{Address, CompiledTeal, Round, SuggestedTransactionParams, ToMsgPack}; -use algonaut_encoding::decode_base64; -use algonaut_model::algod::v2::{ - Account, Application, Asset, Block, BlockWithCertificate, Catchup, DryrunRequest, - DryrunResponse, GenesisBlock, KeyRegistration, NodeStatus, PendingTransaction, - PendingTransactions, Supply, TransactionParams, TransactionResponse, Version, +use crate::Error; +use algonaut_algod::{ + apis::configuration::{ApiKey, Configuration}, + models::{ + self, Account, AccountApplicationInformation200Response, Application, Asset, DryrunRequest, + GetApplicationBoxes200Response, GetBlock200Response, GetBlockHash200Response, + GetPendingTransactionsByAddress200Response, GetStatus200Response, GetSupply200Response, + GetSyncRound200Response, GetTransactionProof200Response, LightBlockHeaderProof, + PendingTransactionResponse, RawTransaction200Response, SimulateRequest, + SimulateTransaction200Response, StateProof, TealDisassemble200Response, + TealDryrun200Response, TransactionParams200Response, Version, + }, }; +use algonaut_core::{CompiledTeal, ToMsgPack}; +use algonaut_encoding::decode_base64; use algonaut_transaction::SignedTransaction; -use crate::error::ServiceError; +use self::error::AlgodError; + +/// Error class wrapping errors from algonaut_algod +pub(crate) mod error; + +pub type Block = GetBlock200Response; #[derive(Debug, Clone)] pub struct Algod { - pub(crate) client: Client, + pub(crate) configuration: Configuration, } impl Algod { @@ -21,255 +33,429 @@ impl Algod { /// For third party providers / custom headers, use [with_headers](Self::with_headers). /// /// Returns an error if the url or token have an invalid format. - pub fn new(url: &str, token: &str) -> Result { - Self::with_headers( - url, - vec![("X-Algo-API-Token", &ApiToken::parse(token)?.to_string())], - ) - } + pub fn new(url: &str, token: &str) -> Result { + let conf = Configuration { + base_path: url.to_owned(), + user_agent: Some("OpenAPI-Generator/0.0.1/rust".to_owned()), + client: reqwest::Client::new(), + basic_auth: None, + oauth_access_token: None, + bearer_access_token: None, + api_key: Some(ApiKey { + prefix: None, + key: token.to_owned(), + }), + }; - /// Build a v2 client for Algorand protocol daemon. - /// - /// Use this initializer when interfacing with third party services, that require custom headers. - /// - /// Returns an error if the url or headers have an invalid format. - pub fn with_headers(url: &str, headers: Headers) -> Result { Ok(Algod { - client: Client::new(url, headers)?, + configuration: conf, }) } - /// Returns the entire genesis file in json. - pub async fn genesis(&self) -> Result { - Ok(self.client.genesis().await?) + /// Given a specific account public key and application ID, this call returns the account's application local state and global state (AppLocalState and AppParams, if either exists). Global state will only be returned if the provided address is the application's creator. + pub async fn account_app( + self, + address: &str, + application_id: u64, + ) -> Result { + Ok( + algonaut_algod::apis::public_api::account_application_information( + &self.configuration, + address, + application_id, + None, + ) + .await + .map_err(Into::::into)?, + ) } - /// Returns Ok if healthy - pub async fn health(&self) -> Result<(), ServiceError> { - Ok(self.client.health().await?) + /// Given a specific account public key, this call returns the accounts status, balance and spendable amounts + pub async fn account(&self, address: &str) -> Result { + Ok(algonaut_algod::apis::public_api::account_information( + &self.configuration, + address, + None, + None, + ) + .await + .map_err(Into::::into)?) } - /// Return metrics about algod functioning. - pub async fn metrics(&self) -> Result { - Ok(self.client.metrics().await?) + /// Returns wether the experimental API are enabled + pub async fn experimental(&self) -> Result<(), Error> { + Ok( + algonaut_algod::apis::public_api::experimental_check(&self.configuration) + .await + .map_err(Into::::into)?, + ) } - /// Get account information. - /// Description Given a specific account public key, this call returns the accounts status, - /// balance and spendable amounts - pub async fn account_information(&self, address: &Address) -> Result { - Ok(self - .client - .account_information(&address.to_string()) - .await?) + /// Given an application ID and box name, it returns the box name and value (each base64 encoded). Box names must be in the goal app call arg encoding form 'encoding:value'. For ints, use the form 'int:1234'. For raw bytes, use the form 'b64:A=='. For printable strings, use the form 'str:hello'. For addresses, use the form 'addr:XYZ...'. + pub async fn app_box(&self, application_id: u64, name: &str) -> Result { + Ok( + algonaut_algod::apis::public_api::get_application_box_by_name( + &self.configuration, + application_id, + name, + ) + .await + .map_err(Into::::into)?, + ) } - /// Get a list of unconfirmed transactions currently in the transaction pool by address. - /// Description: Get the list of pending transactions by address, sorted by priority, - /// in decreasing order, truncated at the end at MAX. If MAX = 0, returns all pending transactions. - pub async fn pending_transactions_for( + /// Given an application ID, return all Box names. No particular ordering is guaranteed. Request fails when client or server-side configured limits prevent returning all Box names. + pub async fn app_boxes( &self, - address: &Address, - max: u64, - ) -> Result { - Ok(self - .client - .pending_transactions_for(&address.to_string(), max) - .await?) + application_id: u64, + max: Option, + ) -> Result { + Ok(algonaut_algod::apis::public_api::get_application_boxes( + &self.configuration, + application_id, + max, + ) + .await + .map_err(Into::::into)?) } - /// Get application information. - /// - /// Given a application id, it returns application information including creator, - /// approval and clear programs, global and local schemas, and global state. - pub async fn application_information(&self, id: u64) -> Result { - Ok(self.client.application_information(id).await?) + /// Given a application ID, it returns application information including creator, approval and clear programs, global and local schemas, and global state. + pub async fn app(&self, application_id: u64) -> Result { + Ok(algonaut_algod::apis::public_api::get_application_by_id( + &self.configuration, + application_id, + ) + .await + .map_err(Into::::into)?) } - /// Get asset information. - /// - /// Given a asset id, it returns asset information including creator, name, - /// total supply and special addresses. - pub async fn asset_information(&self, id: u64) -> Result { - Ok(self.client.asset_information(id).await?) + /// Given a asset ID, it returns asset information including creator, name, total supply and special addresses. + pub async fn asset(&self, asset_id: u64) -> Result { + Ok( + algonaut_algod::apis::public_api::get_asset_by_id(&self.configuration, asset_id) + .await + .map_err(Into::::into)?, + ) } /// Get the block for the given round. - pub async fn block(&self, round: Round) -> Result { - Ok(self.client.block(round).await?) + pub async fn block(&self, round: u64) -> Result { + Ok( + algonaut_algod::apis::public_api::get_block(&self.configuration, round, None) + .await + .map_err(Into::::into)?, + ) } - pub async fn block_with_certificate( + /// Get the block hash for the block on the given round. + pub async fn block_hash(&self, round: u64) -> Result { + Ok( + algonaut_algod::apis::public_api::get_block_hash(&self.configuration, round) + .await + .map_err(Into::::into)?, + ) + } + + /// Returns the entire genesis file in json. + pub async fn genesis(&self) -> Result { + Ok( + algonaut_algod::apis::public_api::get_genesis(&self.configuration) + .await + .map_err(Into::::into)?, + ) + } + + /// Get ledger deltas for a round. + pub async fn state_delta(&self, round: u64) -> Result { + Ok(algonaut_algod::apis::public_api::get_ledger_state_delta( + &self.configuration, + round, + None, + ) + .await + .map_err(Into::::into)?) + } + + /// Gets a proof for a given light block header inside a state proof commitment. + pub async fn light_block_header_proof( + &self, + round: u64, + ) -> Result { + Ok( + algonaut_algod::apis::public_api::get_light_block_header_proof( + &self.configuration, + round, + ) + .await + .map_err(Into::::into)?, + ) + } + + /// Get the list of pending transactions, sorted by priority, in decreasing order, truncated at the end at MAX. If MAX = 0, returns all pending transactions. + pub async fn pending_txns( &self, - round: Round, - ) -> Result { - Ok(self.client.block_with_certificate(round).await?) + max: Option, + ) -> Result { + Ok(algonaut_algod::apis::public_api::get_pending_transactions( + &self.configuration, + max, + None, + ) + .await + .map_err(Into::::into)?) } - /// Starts a catchpoint catchup. - pub async fn start_catchup(&self, catchpoint: &str) -> Result { - Ok(self.client.start_catchup(catchpoint).await?) + /// Get the list of pending transactions by address, sorted by priority, in decreasing order, truncated at the end at MAX. If MAX = 0, returns all pending transactions. + pub async fn address_pending_txns( + &self, + address: &str, + max: Option, + ) -> Result { + Ok( + algonaut_algod::apis::public_api::get_pending_transactions_by_address( + &self.configuration, + address, + max, + None, + ) + .await + .map_err(Into::::into)?, + ) } - /// Aborts a catchpoint catchup. - pub async fn abort_catchup(&self, catchpoint: &str) -> Result { - Ok(self.client.abort_catchup(catchpoint).await?) + /// TODO + pub async fn ready(&self) -> Result<(), Error> { + Ok( + algonaut_algod::apis::public_api::get_ready(&self.configuration) + .await + .map_err(Into::::into)?, + ) + } + + /// Get a state proof that covers a given round. + pub async fn state_proof(&self, round: u64) -> Result { + Ok( + algonaut_algod::apis::public_api::get_state_proof(&self.configuration, round) + .await + .map_err(Into::::into)?, + ) + } + + /// Gets the current node status. + pub async fn status(&self) -> Result { + Ok( + algonaut_algod::apis::public_api::get_status(&self.configuration) + .await + .map_err(Into::::into)?, + ) } /// Get the current supply reported by the ledger. - pub async fn ledger_supply(&self) -> Result { - Ok(self.client.ledger_supply().await?) + pub async fn supply(&self) -> Result { + Ok( + algonaut_algod::apis::public_api::get_supply(&self.configuration) + .await + .map_err(Into::::into)?, + ) } - /// Generate (or renew) and register participation keys on the node for a given account address. - /// - /// address: The account-id to update, or all to update all accounts. - /// fee: The fee to use when submitting key registration transactions. Defaults to the suggested - /// fee. (default = 1000) - /// key-dilution: value to use for two-level participation key. - /// no-wait: Don't wait for transaction to commit before returning response. - /// round-last-valid: The last round for which the generated participation keys will be valid. - pub async fn register_participation_keys( + /// Gets the minimum sync round for the ledger. + pub async fn sync_round(&self) -> Result { + Ok( + algonaut_algod::apis::public_api::get_sync_round(&self.configuration) + .await + .map_err(Into::::into)?, + ) + } + + /// Get a proof for a transaction in a block. + pub async fn txn_proof( &self, - address: &Address, - params: &KeyRegistration, - ) -> Result { - Ok(self - .client - .register_participation_keys(address, params) - .await?) + round: u64, + txid: &str, + ) -> Result { + Ok(algonaut_algod::apis::public_api::get_transaction_proof( + &self.configuration, + round, + txid, + None, + None, + ) + .await + .map_err(Into::::into)?) } - /// Special management endpoint to shutdown the node. Optionally provide a timeout parameter - /// to indicate that the node should begin shutting down after a number of seconds. - pub async fn shutdown(&self, timeout: usize) -> Result<(), ServiceError> { - Ok(self.client.shutdown(timeout).await?) + /// Retrieves the supported API versions, binary build versions, and genesis information. + pub async fn version(&self) -> Result { + Ok( + algonaut_algod::apis::public_api::get_version(&self.configuration) + .await + .map_err(Into::::into)?, + ) } - /// Gets the current node status. - pub async fn status(&self) -> Result { - Ok(self.client.status().await?) + /// Returns Ok if healthy + pub async fn health(&self) -> Result<(), Error> { + Ok( + algonaut_algod::apis::public_api::health_check(&self.configuration) + .await + .map_err(Into::::into)?, + ) } - /// Gets the node status after waiting for the given round. - pub async fn status_after_round(&self, round: Round) -> Result { - Ok(self.client.status_after_round(round).await?) + /// Return metrics about algod functioning. + pub async fn metrics(&self) -> Result<(), Error> { + Ok( + algonaut_algod::apis::public_api::metrics(&self.configuration) + .await + .map_err(Into::::into)?, + ) } - /// Compile TEAL source code to binary, produce its hash. - /// - /// Given TEAL source code in plain text, return compiled program bytes. - /// This endpoint is only enabled when a node's configuration file sets EnableDeveloperAPI to true. - pub async fn compile_teal(&self, teal: &[u8]) -> Result { - let api_compiled_teal = self.client.compile_teal(teal.to_vec()).await?; - // The api result (program + hash) is mapped to the domain program struct, which computes the hash on demand. - // The hash here is redundant and we want to allow to generate it with the SDK too (e.g. for when loading programs from a DB). - // At the moment it seems not warranted to add a cache (so it's initialized with the API hash or lazily), but this can be re-evaluated. - // Note that for contract accounts, there's [ContractAccount](algonaut_transaction::account::ContractAccount), which caches it (as address). - Ok(CompiledTeal(decode_base64( - api_compiled_teal.result.as_bytes(), - )?)) + /// Given a transaction ID of a recently submitted transaction, it returns information about it. There are several cases when this might succeed: - transaction committed (committed round > 0) - transaction still in the pool (committed round = 0, pool error = \"\") - transaction removed from pool due to error (committed round = 0, pool error != \"\") Or the transaction may have happened sufficiently long ago that the node no longer remembers it, and this will return an error. + pub async fn pending_txn(&self, txid: &str) -> Result { + Ok( + algonaut_algod::apis::public_api::pending_transaction_information( + &self.configuration, + txid, + None, + ) + .await + .map_err(Into::::into)?, + ) } - /// Provide debugging information for a transaction (or group). - /// - /// Executes TEAL program(s) in context and returns debugging information about the execution. - /// This endpoint is only enabled when a node's configureation file sets EnableDeveloperAPI - /// to true. - pub async fn dryrun_teal(&self, req: &DryrunRequest) -> Result { - let bytes = req.to_msg_pack()?; - Ok(self.client.dryrun_teal(bytes).await?) + /// Broadcasts a raw transaction or transaction group to the network. + pub async fn send_raw_txn(&self, rawtxn: &[u8]) -> Result { + Ok( + algonaut_algod::apis::public_api::raw_transaction(&self.configuration, rawtxn) + .await + .map_err(Into::::into)?, + ) } /// Broadcasts a transaction to the network. - pub async fn broadcast_signed_transaction( + pub async fn send_txn( &self, txn: &SignedTransaction, - ) -> Result { - self.broadcast_raw_transaction(&txn.to_msg_pack()?).await + ) -> Result { + self.send_raw_txn(&txn.to_msg_pack()?).await } /// Broadcasts a transaction group to the network. /// /// Atomic if the transactions share a [group](algonaut_transaction::transaction::Transaction::group) - pub async fn broadcast_signed_transactions( + pub async fn send_txns( &self, txns: &[SignedTransaction], - ) -> Result { + ) -> Result { let mut bytes = vec![]; for t in txns { bytes.push(t.to_msg_pack()?); } - self.broadcast_raw_transaction(&bytes.concat()).await + self.send_raw_txn(&bytes.concat()).await } - /// Broadcasts raw transactions to the network. - /// - /// When passing multiple transactions, the transactions are atomic if they share a [group](algonaut_transaction::transaction::Transaction::group) - /// - /// Use this when using a third party (e.g. KMD) that delivers directly the serialized signed transaction. - /// - /// Otherwise, prefer [broadcast_signed_transaction](Self::broadcast_signed_transaction) or [broadcast_signed_transactions][Self::broadcast_signed_transactions] + /// Sets the minimum sync round on the ledger. + pub async fn sync(&self, round: u64) -> Result<(), Error> { + Ok( + algonaut_algod::apis::public_api::set_sync_round(&self.configuration, round) + .await + .map_err(Into::::into)?, + ) + } - pub async fn broadcast_raw_transaction( + /// Simulates a raw transaction or transaction group as it would be evaluated on the network. WARNING: This endpoint is experimental and under active development. There are no guarantees in terms of functionality or future support. + pub async fn simulate_txns( &self, - rawtxn: &[u8], - ) -> Result { - Ok(self.client.broadcast_raw_transaction(rawtxn).await?) + request: SimulateRequest, + ) -> Result { + Ok(algonaut_algod::apis::public_api::simulate_transaction( + &self.configuration, + request, + None, + ) + .await + .map_err(Into::::into)?) } - /// Get parameters for constructing a new transaction. - pub async fn transaction_params(&self) -> Result { - Ok(self.client.transaction_params().await?) + /// Returns the entire swagger spec in json. + pub async fn swagger_json(&self) -> Result { + Ok( + algonaut_algod::apis::public_api::swagger_json(&self.configuration) + .await + .map_err(Into::::into)?, + ) } - /// Get suggested parameters for constructing a new transaction. - pub async fn suggested_transaction_params( + /// Given TEAL source code in plain text, return base64 encoded program bytes and base32 SHA512_256 hash of program bytes (Address style). This endpoint is only enabled when a node's configuration file sets EnableDeveloperAPI to true. + pub async fn teal_compile( &self, - ) -> Result { - let params = self.client.transaction_params().await?; - Ok(SuggestedTransactionParams { - genesis_id: params.genesis_id, - genesis_hash: params.genesis_hash, - consensus_version: params.consensus_version, - fee_per_byte: params.fee_per_byte, - min_fee: params.min_fee, - first_valid: params.last_round, - last_valid: params.last_round + 1000, - }) + source: &[u8], + sourcemap: Option, + ) -> Result { + let api_compiled_teal = + algonaut_algod::apis::public_api::teal_compile(&self.configuration, source, sourcemap) + .await + .map_err(Into::::into)?; + // The api result (program + hash) is mapped to the domain program struct, which computes the hash on demand. + // The hash here is redundant and we want to allow to generate it with the SDK too (e.g. for when loading programs from a DB). + // At the moment it seems not warranted to add a cache (so it's initialized with the API hash or lazily), but this can be re-evaluated. + // Note that for contract accounts, there's [ContractAccount](algonaut_transaction::account::ContractAccount), which caches it (as address). + Ok(CompiledTeal(decode_base64( + api_compiled_teal.result.as_bytes(), + )?)) } - /// Get a list of unconfirmed transactions currently in the transaction pool. - /// - /// Get the list of pending transactions, sorted by priority, in decreasing order, - /// truncated at the end at MAX. If MAX = 0, returns all pending transactions. - pub async fn pending_transactions( + /// Given the program bytes, return the TEAL source code in plain text. This endpoint is only enabled when a node's configuration file sets EnableDeveloperAPI to true. + pub async fn teal_disassemble( &self, - max: u64, - ) -> Result { - Ok(self.client.pending_transactions(max).await?) + source: &[u8], + ) -> Result { + Ok( + algonaut_algod::apis::public_api::teal_disassemble(&self.configuration, source) + .await + .map_err(Into::::into)?, + ) } - /// Get a specific pending transaction. - /// - /// Given a transaction id of a recently submitted transaction, it returns information about - /// it. There are several cases when this might succeed: - /// - transaction committed (committed round > 0) - /// - transaction still in the pool (committed round = 0, pool error = "") - /// - transaction removed from pool due to error (committed round = 0, pool error != "") - /// - /// Or the transaction may have happened sufficiently long ago that the node no longer remembers - /// it, and this will return an error. - pub async fn pending_transaction_with_id( + /// Executes TEAL program(s) in context and returns debugging information about the execution. This endpoint is only enabled when a node's configuration file sets EnableDeveloperAPI to true. + pub async fn teal_dryrun( &self, - txid: &str, - ) -> Result { - Ok(self.client.pending_transaction_with_id(txid).await?) + request: Option, + ) -> Result { + Ok( + algonaut_algod::apis::public_api::teal_dryrun(&self.configuration, request) + .await + .map_err(Into::::into)?, + ) + } + + /// Get parameters for constructing a new transaction. + pub async fn txn_params(&self) -> Result { + Ok( + algonaut_algod::apis::public_api::transaction_params(&self.configuration) + .await + .map_err(Into::::into)?, + ) } - /// Retrieves the current version - pub async fn versions(&self) -> Result { - Ok(self.client.versions().await?) + /// Unset the ledger sync round. + pub async fn unsync(&self) -> Result<(), Error> { + Ok( + algonaut_algod::apis::public_api::unset_sync_round(&self.configuration) + .await + .map_err(Into::::into)?, + ) + } + + /// Waits for a block to appear after round {round} and returns the node's status at the time. + pub async fn status_after_block(&self, round: u64) -> Result { + Ok( + algonaut_algod::apis::public_api::wait_for_block(&self.configuration, round) + .await + .map_err(Into::::into)?, + ) } } @@ -285,41 +471,4 @@ mod tests { ); assert!(res.ok().is_some()); } - - #[test] - fn test_client_builder_with_invalid_url() { - let res = Algod::new( - "asfdsdfs", - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - ); - assert!(res.is_err()); - assert!(matches!(res.err().unwrap(), ServiceError::BadUrl(_))); - } - - #[test] - fn test_client_builder_with_invalid_url_no_scheme() { - let res = Algod::new( - "example.com", - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - ); - assert!(res.is_err()); - assert!(matches!(res.err().unwrap(), ServiceError::BadUrl(_))); - } - - #[test] - fn test_client_builder_with_invalid_token() { - let res = Algod::new( - "http://example.com", - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - ); - assert!(res.is_err()); - assert!(res.err().unwrap() == ServiceError::BadToken); - } - - #[test] - fn test_client_builder_with_empty_token() { - let res = Algod::new("http://example.com", ""); - assert!(res.is_err()); - assert!(res.err().unwrap() == ServiceError::BadToken); - } } diff --git a/src/atomic_transaction_composer/mod.rs b/src/atomic_transaction_composer/mod.rs index d820929f..6564ef18 100644 --- a/src/atomic_transaction_composer/mod.rs +++ b/src/atomic_transaction_composer/mod.rs @@ -8,11 +8,10 @@ use algonaut_abi::{ abi_type::{AbiType, AbiValue}, make_tuple_type, }; -use algonaut_core::{Address, CompiledTeal, SuggestedTransactionParams}; +use algonaut_algod::models::{PendingTransactionResponse, TransactionParams200Response}; +use algonaut_core::{Address, CompiledTeal, MicroAlgos}; use algonaut_crypto::HashDigest; -use algonaut_model::algod::v2::PendingTransaction; use algonaut_transaction::{ - builder::TxnFee, error::TransactionError, transaction::{ to_tx_type_enum, ApplicationCallOnComplete, ApplicationCallTransaction, StateSchema, @@ -25,9 +24,7 @@ use num_bigint::BigUint; use num_traits::ToPrimitive; use std::collections::HashMap; -use crate::{ - algod::v2::Algod, error::ServiceError, util::wait_for_pending_tx::wait_for_pending_transaction, -}; +use crate::{algod::v2::Algod, util::wait_for_pending_tx::wait_for_pending_transaction, Error}; use self::transaction_signer::TransactionSigner; @@ -57,7 +54,7 @@ pub struct AbiMethodResult { /// The TxID of the transaction that invoked the ABI method call. pub tx_id: String, /// Information about the confirmed transaction that invoked the ABI method call. - pub tx_info: PendingTransaction, + pub tx_info: PendingTransactionResponse, /// The method's return value pub return_value: Result, } @@ -80,11 +77,11 @@ pub struct AddMethodCallParams { /// The arguments to include in the method call. If omitted, no arguments will be passed to the method. pub method_args: Vec, /// Fee - pub fee: TxnFee, + pub fee: MicroAlgos, /// The address of the sender of this application call pub sender: Address, /// Transactions params to use for this application call - pub suggested_params: SuggestedTransactionParams, + pub suggested_params: TransactionParams200Response, /// The OnComplete action to take for this application call pub on_complete: ApplicationCallOnComplete, /// The approval program for this application call. Only set this if this is an application @@ -228,18 +225,15 @@ impl AtomicTransactionComposer { /// /// An error will be thrown if the composer's status is not Building, /// or if adding this transaction causes the current group to exceed MaxAtomicGroupSize. - pub fn add_transaction( - &mut self, - txn_with_signer: TransactionWithSigner, - ) -> Result<(), ServiceError> { + pub fn add_transaction(&mut self, txn_with_signer: TransactionWithSigner) -> Result<(), Error> { if self.status != AtomicTransactionComposerStatus::Building { - return Err(ServiceError::Msg( + return Err(Error::Msg( "status must be BUILDING in order to add transactions".to_owned(), )); } if self.len() == MAX_ATOMIC_GROUP_SIZE { - return Err(ServiceError::Msg(format!( + return Err(Error::Msg(format!( "reached max group size: {MAX_ATOMIC_GROUP_SIZE}" ))); } @@ -251,24 +245,21 @@ impl AtomicTransactionComposer { Ok(()) } - pub fn add_method_call( - &mut self, - params: &mut AddMethodCallParams, - ) -> Result<(), ServiceError> { + pub fn add_method_call(&mut self, params: &mut AddMethodCallParams) -> Result<(), Error> { if self.status != AtomicTransactionComposerStatus::Building { - return Err(ServiceError::Msg( + return Err(Error::Msg( "status must be BUILDING in order to add transactions".to_owned(), )); } if params.method_args.len() != params.method.args.len() { - return Err(ServiceError::Msg(format!( + return Err(Error::Msg(format!( "incorrect number of arguments were provided: {} != {}", params.method_args.len(), params.method.args.len() ))); } if self.len() + params.method.get_tx_count() > MAX_ATOMIC_GROUP_SIZE { - return Err(ServiceError::Msg(format!( + return Err(Error::Msg(format!( "reached max group size: {MAX_ATOMIC_GROUP_SIZE}" ))); } @@ -336,8 +327,7 @@ impl AtomicTransactionComposer { extra_pages: params.extra_pages, }); - let mut tx_builder = - TxnBuilder::with_fee(¶ms.suggested_params, params.fee.clone(), app_call); + let mut tx_builder = TxnBuilder::with_fee(¶ms.suggested_params, params.fee, app_call); if let Some(rekey_to) = params.rekey_to { tx_builder = tx_builder.rekey_to(rekey_to); } @@ -363,13 +353,13 @@ impl AtomicTransactionComposer { /// Finalize the transaction group and returned the finalized transactions. /// The composer's status will be at least BUILT after executing this method. - pub fn build_group(&mut self) -> Result, ServiceError> { + pub fn build_group(&mut self) -> Result, Error> { if self.status >= AtomicTransactionComposerStatus::Built { return Ok(self.txs.clone()); } if self.txs.is_empty() { - return Err(ServiceError::Msg( + return Err(Error::Msg( "should not build transaction group with 0 transactions in composer".to_owned(), )); } else if self.txs.len() > 1 { @@ -384,7 +374,7 @@ impl AtomicTransactionComposer { Ok(self.txs.clone()) } - pub fn gather_signatures(&mut self) -> Result, ServiceError> { + pub fn gather_signatures(&mut self) -> Result, Error> { if self.status >= AtomicTransactionComposerStatus::Signed { return Ok(self.signed_txs.clone()); } @@ -411,7 +401,7 @@ impl AtomicTransactionComposer { } if indices_to_sign.is_empty() { - return Err(ServiceError::Msg( + return Err(Error::Msg( "invalid tx signer provided, isn't equal to self".to_owned(), )); } @@ -437,27 +427,25 @@ impl AtomicTransactionComposer { .collect() } - pub async fn submit(&mut self, algod: &Algod) -> Result, ServiceError> { + pub async fn submit(&mut self, algod: &Algod) -> Result, Error> { if self.status >= AtomicTransactionComposerStatus::Submitted { - return Err(ServiceError::Msg( + return Err(Error::Msg( "Atomic Transaction Composer cannot submit committed transaction".to_owned(), )); } self.gather_signatures()?; - algod - .broadcast_signed_transactions(&self.signed_txs) - .await?; + algod.send_txns(&self.signed_txs).await?; self.status = AtomicTransactionComposerStatus::Submitted; Ok(self.get_txs_ids()) } - pub async fn execute(&mut self, algod: &Algod) -> Result { + pub async fn execute(&mut self, algod: &Algod) -> Result { if self.status >= AtomicTransactionComposerStatus::Committed { - return Err(ServiceError::Msg("status is already committed".to_owned())); + return Err(Error::Msg("status is already committed".to_owned())); } self.submit(algod).await?; @@ -488,7 +476,7 @@ impl AtomicTransactionComposer { if i != index_to_wait { let tx_id = self.signed_txs[i].transaction_id.clone(); - match algod.pending_transaction_with_id(&tx_id).await { + match algod.pending_txn(&tx_id).await { Ok(p) => { current_tx_id = tx_id; current_pending_tx = p; @@ -521,10 +509,10 @@ impl AtomicTransactionComposer { } fn get_return_value_with_return_type( - pending_tx: &PendingTransaction, + pending_tx: &PendingTransactionResponse, tx_id: &str, // our txn in PendingTransaction currently has no fields, so the tx id is passed separately return_type: AbiReturnType, -) -> Result { +) -> Result { let return_value = match return_type { AbiReturnType::Some(return_type) => { get_return_value_with_abi_type(pending_tx, &return_type)? @@ -539,13 +527,13 @@ fn get_return_value_with_return_type( }) } -impl From for ServiceError { +impl From for Error { fn from(e: TransactionError) -> Self { Self::Msg(format!("{e:?}")) } } -impl From for ServiceError { +impl From for Error { fn from(e: AbiError) -> Self { match e { AbiError::Msg(msg) => Self::Msg(msg), @@ -553,15 +541,15 @@ impl From for ServiceError { } } -fn validate_tx(tx: &Transaction, expected_type: TransactionArgType) -> Result<(), ServiceError> { +fn validate_tx(tx: &Transaction, expected_type: TransactionArgType) -> Result<(), Error> { if tx.group.is_some() { - return Err(ServiceError::Msg("Expected empty group id".to_owned())); + return Err(Error::Msg("Expected empty group id".to_owned())); } if expected_type != TransactionArgType::Any && expected_type != TransactionArgType::One(to_tx_type_enum(&tx.txn_type)) { - return Err(ServiceError::Msg(format!( + return Err(Error::Msg(format!( "expected transaction with type {expected_type:?}, but got type {:?}", tx.txn_type ))); @@ -574,11 +562,11 @@ fn add_tx_arg_type_to_method_call( arg_value: &AbiArgValue, expected_type: TransactionArgType, txs_with_signer: &mut Vec, -) -> Result<(), ServiceError> { +) -> Result<(), Error> { let txn_and_signer = match arg_value { AbiArgValue::TxWithSigner(tx_with_signer) => tx_with_signer, _ => { - return Err(ServiceError::Msg( + return Err(Error::Msg( "invalid arg value, expected transaction".to_owned(), )); } @@ -595,14 +583,14 @@ fn add_abi_obj_arg_to_method_call( arg_value: &AbiArgValue, method_types: &mut Vec, method_args: &mut Vec, -) -> Result<(), ServiceError> { +) -> Result<(), Error> { match arg_value { AbiArgValue::AbiValue(value) => { method_types.push(abi_type.clone()); method_args.push(value.clone()); } AbiArgValue::TxWithSigner(_) => { - return Err(ServiceError::Msg( + return Err(Error::Msg( "Invalid state: shouldn't be here with a tx with signer value type".to_owned(), )); } @@ -625,7 +613,7 @@ fn add_ref_arg_to_method_call( sender: Address, app_id: u64, -) -> Result<(), ServiceError> { +) -> Result<(), Error> { let index = add_to_foreign_array( arg_type, arg_value, @@ -652,7 +640,7 @@ fn add_to_foreign_array( foreign_apps: &mut Vec, sender: Address, app_id: u64, -) -> Result { +) -> Result { match arg_type { ReferenceArgType::Account => match arg_value.address() { Some(address) => Ok(populate_foreign_array( @@ -660,7 +648,7 @@ fn add_to_foreign_array( foreign_accounts, Some(sender), )), - _ => Err(ServiceError::Msg(format!( + _ => Err(Error::Msg(format!( "Invalid value type: {arg_value:?} for arg type: {arg_type:?}" ))), }, @@ -672,7 +660,7 @@ fn add_to_foreign_array( Ok(populate_foreign_array(intu64, foreign_assets, None)) } - _ => Err(ServiceError::Msg(format!( + _ => Err(Error::Msg(format!( "Invalid value type: {arg_value:?} for arg type: {arg_type:?}" ))), }, @@ -684,7 +672,7 @@ fn add_to_foreign_array( Ok(populate_foreign_array(intu64, foreign_apps, Some(app_id))) } - _ => Err(ServiceError::Msg(format!( + _ => Err(Error::Msg(format!( "Invalid value type: {arg_value:?} for arg type: {arg_type:?}" ))), }, @@ -694,7 +682,7 @@ fn add_to_foreign_array( fn wrap_overflowing_values( method_types: &[AbiType], method_args: &[AbiValue], -) -> Result<(AbiType, AbiValue), ServiceError> { +) -> Result<(AbiType, AbiValue), Error> { let mut wrapped_abi_types = vec![]; let mut wrapped_value_list = vec![]; @@ -743,23 +731,32 @@ fn populate_foreign_array( } fn get_return_value_with_abi_type( - pending_tx: &PendingTransaction, + pending_tx: &PendingTransactionResponse, abi_type: &AbiType, -) -> Result, ServiceError> { - if pending_tx.logs.is_empty() { - return Err(ServiceError::Msg( +) -> Result, Error> { + if pending_tx.logs.is_none() { + return Err(Error::Msg( + "App call transaction did not log a return value".to_owned(), + )); + } + + // safe to unwrap given the previous check + let logs = &pending_tx.logs.clone().unwrap(); + + if logs.is_empty() { + return Err(Error::Msg( "App call transaction did not log a return value".to_owned(), )); } - let ret_line = &pending_tx.logs[pending_tx.logs.len() - 1]; + let ret_line = &logs[logs.len() - 1]; let decoded_ret_line: Vec = BASE64 - .decode(ret_line.as_bytes()) - .map_err(|e| ServiceError::Msg(format!("BASE64 Decoding error: {e:?}")))?; + .decode(&ret_line.0[..]) + .map_err(|e| Error::Msg(format!("BASE64 Decoding error: {e:?}")))?; if !check_log_ret(&decoded_ret_line) { - return Err(ServiceError::Msg( + return Err(Error::Msg( "App call transaction did not log a return value(2)".to_owned(), )); } diff --git a/src/error.rs b/src/error.rs index af2d4062..a43087f2 100644 --- a/src/error.rs +++ b/src/error.rs @@ -2,7 +2,7 @@ use std::fmt::Debug; use thiserror::Error; #[derive(Error, Clone, Debug, PartialEq, Eq)] -pub enum ServiceError { +pub enum Error { /// URL parse error. #[error("Url parsing error.")] BadUrl(String), @@ -31,7 +31,7 @@ pub enum ServiceError { Internal(String), } -impl ServiceError { +impl Error { /// Returns if the error is a `RequestError` that failed with a status code of 404. pub fn is_404(&self) -> bool { if let Some(e) = self.as_request_error() { @@ -93,53 +93,95 @@ impl RequestErrorDetails { } } -impl From for ServiceError { - fn from(error: algonaut_client::error::ClientError) -> Self { +impl From for Error { + fn from(error: crate::algod::v2::error::AlgodError) -> Self { match error { - algonaut_client::error::ClientError::BadUrl(msg) => ServiceError::BadUrl(msg), - algonaut_client::error::ClientError::BadToken => ServiceError::BadToken, - algonaut_client::error::ClientError::BadHeader(msg) => ServiceError::BadHeader(msg), - algonaut_client::error::ClientError::Request(e) => ServiceError::Request(e.into()), - algonaut_client::error::ClientError::Msg(msg) => ServiceError::Msg(msg), + crate::algod::v2::error::AlgodError::Msg(msg) => Error::Msg(msg), } } } -impl From for RequestError { - fn from(error: algonaut_client::error::RequestError) -> Self { +impl From for Error { + fn from(error: algonaut_indexer::error::ClientError) -> Self { + match error { + algonaut_indexer::error::ClientError::BadUrl(msg) => Error::BadUrl(msg), + algonaut_indexer::error::ClientError::BadToken => Error::BadToken, + algonaut_indexer::error::ClientError::BadHeader(msg) => Error::BadHeader(msg), + algonaut_indexer::error::ClientError::Request(e) => Error::Request(e.into()), + algonaut_indexer::error::ClientError::Msg(msg) => Error::Msg(msg), + } + } +} + +impl From for RequestError { + fn from(error: algonaut_indexer::error::RequestError) -> Self { + RequestError::new(error.url.clone(), error.details.into()) + } +} + +impl From for RequestErrorDetails { + fn from(details: algonaut_indexer::error::RequestErrorDetails) -> Self { + match details { + algonaut_indexer::error::RequestErrorDetails::Http { status, message } => { + RequestErrorDetails::Http { status, message } + } + algonaut_indexer::error::RequestErrorDetails::Timeout => { + RequestErrorDetails::Timeout {} + } + algonaut_indexer::error::RequestErrorDetails::Client { description } => { + RequestErrorDetails::Client { description } + } + } + } +} + +impl From for Error { + fn from(error: algonaut_kmd::error::ClientError) -> Self { + match error { + algonaut_kmd::error::ClientError::BadUrl(msg) => Error::BadUrl(msg), + algonaut_kmd::error::ClientError::BadToken => Error::BadToken, + algonaut_kmd::error::ClientError::BadHeader(msg) => Error::BadHeader(msg), + algonaut_kmd::error::ClientError::Request(e) => Error::Request(e.into()), + algonaut_kmd::error::ClientError::Msg(msg) => Error::Msg(msg), + } + } +} + +impl From for RequestError { + fn from(error: algonaut_kmd::error::RequestError) -> Self { RequestError::new(error.url.clone(), error.details.into()) } } -impl From for RequestErrorDetails { - fn from(details: algonaut_client::error::RequestErrorDetails) -> Self { +impl From for RequestErrorDetails { + fn from(details: algonaut_kmd::error::RequestErrorDetails) -> Self { match details { - algonaut_client::error::RequestErrorDetails::Http { status, message } => { + algonaut_kmd::error::RequestErrorDetails::Http { status, message } => { RequestErrorDetails::Http { status, message } } - algonaut_client::error::RequestErrorDetails::Timeout => RequestErrorDetails::Timeout {}, - algonaut_client::error::RequestErrorDetails::Client { description } => { + algonaut_kmd::error::RequestErrorDetails::Timeout => RequestErrorDetails::Timeout {}, + algonaut_kmd::error::RequestErrorDetails::Client { description } => { RequestErrorDetails::Client { description } } } } } -impl From for ServiceError { +impl From for Error { fn from(error: rmp_serde::encode::Error) -> Self { - ServiceError::Internal(error.to_string()) + Error::Internal(error.to_string()) } } -impl From for ServiceError { +impl From for Error { fn from(error: String) -> Self { - ServiceError::Internal(error) + Error::Internal(error) } } #[test] fn check_404() { - let not_found_error = ServiceError::Request(RequestError::new( + let not_found_error = Error::Request(RequestError::new( Some("testing".to_owned()), RequestErrorDetails::Http { status: 404, @@ -147,7 +189,7 @@ fn check_404() { }, )); - let bad_request_error = ServiceError::Request(RequestError::new( + let bad_request_error = Error::Request(RequestError::new( None, RequestErrorDetails::Http { status: 400, @@ -155,7 +197,7 @@ fn check_404() { }, )); - let unrelated_error = ServiceError::UnitializedToken; + let unrelated_error = Error::UnitializedToken; assert!( not_found_error.is_404(), diff --git a/src/indexer/v2/mod.rs b/src/indexer/v2/mod.rs index 901b65d7..aafdda20 100644 --- a/src/indexer/v2/mod.rs +++ b/src/indexer/v2/mod.rs @@ -1,5 +1,5 @@ -use algonaut_client::{indexer::v2::Client, Headers}; use algonaut_core::{Address, Round}; +use algonaut_indexer::{indexer::v2::Client, Headers}; use algonaut_model::indexer::v2::{ AccountInfoResponse, AccountResponse, AccountTransactionResponse, ApplicationInfoResponse, ApplicationResponse, AssetResponse, AssetTransactionResponse, AssetsInfoResponse, @@ -8,7 +8,7 @@ use algonaut_model::indexer::v2::{ QueryBalances, QueryTransaction, TransactionInfoResponse, TransactionResponse, }; -use crate::error::ServiceError; +use crate::Error; #[derive(Debug, Clone)] pub struct Indexer { @@ -21,7 +21,7 @@ impl Indexer { /// For third party providers / custom headers, use [with_headers](Self::with_headers). /// /// Returns an error if the url has an invalid format. - pub fn new(url: &str) -> Result { + pub fn new(url: &str) -> Result { Self::with_headers(url, vec![]) } @@ -30,19 +30,19 @@ impl Indexer { /// Use this initializer when interfacing with third party services, that require custom headers. /// /// Returns an error if the url or the headers have an invalid format. - pub fn with_headers(url: &str, headers: Headers) -> Result { + pub fn with_headers(url: &str, headers: Headers) -> Result { Ok(Indexer { client: Client::new(url, headers)?, }) } /// Returns Ok if healthy - pub async fn health(&self) -> Result<(), ServiceError> { + pub async fn health(&self) -> Result<(), Error> { Ok(self.client.health().await?) } /// Search for accounts. - pub async fn accounts(&self, query: &QueryAccount) -> Result { + pub async fn accounts(&self, query: &QueryAccount) -> Result { Ok(self.client.accounts(query).await?) } @@ -51,7 +51,7 @@ impl Indexer { &self, address: &Address, query: &QueryAccountInfo, - ) -> Result { + ) -> Result { Ok(self.client.account_info(address, query).await?) } @@ -60,7 +60,7 @@ impl Indexer { &self, address: &Address, query: &QueryAccountTransaction, - ) -> Result { + ) -> Result { Ok(self.client.account_transactions(address, query).await?) } @@ -68,7 +68,7 @@ impl Indexer { pub async fn applications( &self, query: &QueryApplications, - ) -> Result { + ) -> Result { Ok(self.client.applications(query).await?) } @@ -77,12 +77,12 @@ impl Indexer { &self, id: u64, query: &QueryApplicationInfo, - ) -> Result { + ) -> Result { Ok(self.client.application_info(id, query).await?) } /// Search for assets. - pub async fn assets(&self, query: &QueryAssets) -> Result { + pub async fn assets(&self, query: &QueryAssets) -> Result { Ok(self.client.assets(query).await?) } @@ -91,7 +91,7 @@ impl Indexer { &self, id: u64, query: &QueryAssetsInfo, - ) -> Result { + ) -> Result { Ok(self.client.assets_info(id, query).await?) } @@ -100,7 +100,7 @@ impl Indexer { &self, id: u64, query: &QueryBalances, - ) -> Result { + ) -> Result { Ok(self.client.asset_balances(id, query).await?) } @@ -109,12 +109,12 @@ impl Indexer { &self, id: u64, query: &QueryAssetTransaction, - ) -> Result { + ) -> Result { Ok(self.client.asset_transactions(id, query).await?) } /// Lookup block. - pub async fn block(&self, round: Round) -> Result { + pub async fn block(&self, round: Round) -> Result { Ok(self.client.block(round).await?) } @@ -122,15 +122,12 @@ impl Indexer { pub async fn transactions( &self, query: &QueryTransaction, - ) -> Result { + ) -> Result { Ok(self.client.transactions(query).await?) } /// Search for transactions. - pub async fn transaction_info( - &self, - id: &str, - ) -> Result { + pub async fn transaction_info(&self, id: &str) -> Result { Ok(self.client.transaction_info(id).await?) } } diff --git a/src/kmd/v1/mod.rs b/src/kmd/v1/mod.rs index 85c739e7..fd60e4ab 100644 --- a/src/kmd/v1/mod.rs +++ b/src/kmd/v1/mod.rs @@ -1,6 +1,7 @@ -use algonaut_client::{kmd::v1::Client, token::ApiToken, Headers}; +use crate::Error; use algonaut_core::{Address, MultisigSignature, ToMsgPack}; use algonaut_crypto::{Ed25519PublicKey, MasterDerivationKey}; +use algonaut_kmd::{kmd::v1::Client, token::ApiToken, Headers}; use algonaut_model::kmd::v1::{ CreateWalletResponse, DeleteKeyResponse, DeleteMultisigResponse, ExportKeyResponse, ExportMasterDerivationKeyResponse, ExportMultisigResponse, GenerateKeyResponse, @@ -11,8 +12,6 @@ use algonaut_model::kmd::v1::{ }; use algonaut_transaction::Transaction; -use crate::error::ServiceError; - #[derive(Debug, Clone)] pub struct Kmd { pub(crate) client: Client, @@ -24,7 +23,7 @@ impl Kmd { /// For third party providers / custom headers, use [with_headers](Self::with_headers). /// /// Returns an error if the url or token have an invalid format. - pub fn new(url: &str, token: &str) -> Result { + pub fn new(url: &str, token: &str) -> Result { Self::with_headers( url, vec![("X-KMD-API-Token", &ApiToken::parse(token)?.to_string())], @@ -36,19 +35,19 @@ impl Kmd { /// Use this initializer when interfacing with third party services, that require custom headers. /// /// Returns an error if the url or headers have an invalid format. - pub fn with_headers(url: &str, headers: Headers) -> Result { + pub fn with_headers(url: &str, headers: Headers) -> Result { Ok(Kmd { client: Client::new(url, headers)?, }) } /// Retrieves the current version - pub async fn versions(&self) -> Result { + pub async fn versions(&self) -> Result { Ok(self.client.versions().await?) } /// List all of the wallets that kmd is aware of - pub async fn list_wallets(&self) -> Result { + pub async fn list_wallets(&self) -> Result { Ok(self.client.list_wallets().await?) } @@ -59,7 +58,7 @@ impl Kmd { wallet_password: &str, wallet_driver_name: &str, master_derivation_key: MasterDerivationKey, - ) -> Result { + ) -> Result { Ok(self .client .create_wallet( @@ -81,7 +80,7 @@ impl Kmd { &self, wallet_id: &str, wallet_password: &str, - ) -> Result { + ) -> Result { Ok(self .client .init_wallet_handle(wallet_id, wallet_password) @@ -92,7 +91,7 @@ impl Kmd { pub async fn release_wallet_handle( &self, wallet_handle: &str, - ) -> Result { + ) -> Result { Ok(self.client.release_wallet_handle(wallet_handle).await?) } @@ -100,7 +99,7 @@ impl Kmd { pub async fn renew_wallet_handle( &self, wallet_handle: &str, - ) -> Result { + ) -> Result { Ok(self.client.renew_wallet_handle(wallet_handle).await?) } @@ -110,7 +109,7 @@ impl Kmd { wallet_id: &str, wallet_password: &str, new_name: &str, - ) -> Result { + ) -> Result { Ok(self .client .rename_wallet(wallet_id, wallet_password, new_name) @@ -121,7 +120,7 @@ impl Kmd { pub async fn get_wallet_info( &self, wallet_handle: &str, - ) -> Result { + ) -> Result { Ok(self.client.get_wallet_info(wallet_handle).await?) } @@ -130,7 +129,7 @@ impl Kmd { &self, wallet_handle: &str, wallet_password: &str, - ) -> Result { + ) -> Result { Ok(self .client .export_master_derivation_key(wallet_handle, wallet_password) @@ -142,7 +141,7 @@ impl Kmd { &self, wallet_handle: &str, private_key: [u8; 32], - ) -> Result { + ) -> Result { Ok(self.client.import_key(wallet_handle, private_key).await?) } @@ -154,7 +153,7 @@ impl Kmd { wallet_handle: &str, wallet_password: &str, address: &Address, - ) -> Result { + ) -> Result { Ok(self .client .export_key(wallet_handle, wallet_password, address) @@ -162,10 +161,7 @@ impl Kmd { } /// Generates a key and adds it to the wallet, returning the public key - pub async fn generate_key( - &self, - wallet_handle: &str, - ) -> Result { + pub async fn generate_key(&self, wallet_handle: &str) -> Result { Ok(self.client.generate_key(wallet_handle).await?) } @@ -175,7 +171,7 @@ impl Kmd { wallet_handle: &str, wallet_password: &str, address: &str, - ) -> Result { + ) -> Result { Ok(self .client .delete_key(wallet_handle, wallet_password, address) @@ -183,7 +179,7 @@ impl Kmd { } /// List all of the public keys in the wallet - pub async fn list_keys(&self, wallet_handle: &str) -> Result { + pub async fn list_keys(&self, wallet_handle: &str) -> Result { Ok(self.client.list_keys(wallet_handle).await?) } @@ -193,7 +189,7 @@ impl Kmd { wallet_handle: &str, wallet_password: &str, transaction: &Transaction, - ) -> Result { + ) -> Result { Ok(self .client .sign_transaction(wallet_handle, wallet_password, transaction.to_msg_pack()?) @@ -201,10 +197,7 @@ impl Kmd { } /// Lists all of the multisig accounts whose preimages this wallet stores - pub async fn list_multisig( - &self, - wallet_handle: &str, - ) -> Result { + pub async fn list_multisig(&self, wallet_handle: &str) -> Result { Ok(self.client.list_multisig(wallet_handle).await?) } @@ -215,7 +208,7 @@ impl Kmd { version: u8, threshold: u8, pks: &[Ed25519PublicKey], - ) -> Result { + ) -> Result { Ok(self .client .import_multisig(wallet_handle, version, threshold, pks) @@ -227,7 +220,7 @@ impl Kmd { &self, wallet_handle: &str, address: &str, - ) -> Result { + ) -> Result { Ok(self.client.export_multisig(wallet_handle, address).await?) } @@ -237,7 +230,7 @@ impl Kmd { wallet_handle: &str, wallet_password: &str, address: &str, - ) -> Result { + ) -> Result { Ok(self .client .delete_multisig(wallet_handle, wallet_password, address) @@ -254,7 +247,7 @@ impl Kmd { transaction: &Transaction, public_key: Ed25519PublicKey, partial_multisig: Option, - ) -> Result { + ) -> Result { Ok(self .client .sign_multisig_transaction( diff --git a/src/lib.rs b/src/lib.rs index d8e8d1c6..1662cebf 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -12,9 +12,17 @@ pub use algonaut_crypto as crypto; pub use algonaut_model as model; pub use algonaut_transaction as transaction; +pub use algonaut_algod as openapi_algod; +pub use algonaut_indexer as openapi_indexer; +pub use algonaut_kmd as openapi_kmd; + pub mod algod; -pub mod atomic_transaction_composer; -pub mod error; pub mod indexer; pub mod kmd; + +pub mod atomic_transaction_composer; + +pub mod error; +pub use error::Error; + pub mod util; diff --git a/src/util/dryrun_printer.rs b/src/util/dryrun_printer.rs index a944d29f..9ef7cced 100644 --- a/src/util/dryrun_printer.rs +++ b/src/util/dryrun_printer.rs @@ -1,9 +1,10 @@ -use crate::{algod::v2::Algod, error::ServiceError}; -use algonaut_core::{to_app_address, Address, Round}; -use algonaut_model::algod::v2::{ +use crate::{algod::v2::Algod, Error}; +use algonaut_algod::models::{ Application, ApplicationParams, ApplicationStateSchema, DryrunRequest, DryrunState, DryrunTxnResult, TealValue, }; +use algonaut_core::{to_app_address, Address}; +use algonaut_encoding::Bytes; use algonaut_transaction::{ transaction::{ApplicationCallTransaction, StateSchema}, SignedTransaction, TransactionType, @@ -17,8 +18,8 @@ const DEFAULT_MAX_WIDTH: usize = 30; pub async fn create_dryrun( algod: &Algod, signed_txs: &[SignedTransaction], -) -> Result { - create_dryrun_with_settings(algod, signed_txs, "", 0, Round(0)).await +) -> Result { + create_dryrun_with_settings(algod, signed_txs, "", 0, 0).await } pub async fn create_dryrun_with_settings( @@ -26,10 +27,10 @@ pub async fn create_dryrun_with_settings( signed_txs: &[SignedTransaction], protocol_version: &str, latest_timestamp: u64, - round: Round, -) -> Result { + round: u64, +) -> Result { if signed_txs.is_empty() { - return Err(ServiceError::Msg("No txs".to_owned())); + return Err(Error::Msg("No txs".to_owned())); } // The details we need to add to DryrunRequest object @@ -67,18 +68,18 @@ pub async fn create_dryrun_with_settings( } for asset_id in assets { - let asset = algod.asset_information(asset_id).await?; - accts.insert(asset.params.creator); + let asset = algod.asset(asset_id).await?; + accts.insert(asset.params.creator.parse().unwrap()); } for app_id in apps { - let app = algod.application_information(app_id).await?; - accts.insert(app.params.creator); + let app = algod.app(app_id).await?; + accts.insert(app.params.creator.parse().unwrap()); app_infos.push(app); } for address in accts { - let acc = algod.account_information(&address).await?; + let acc = algod.account(address.to_string().as_str()).await?; acct_infos.push(acc); } @@ -95,31 +96,39 @@ pub async fn create_dryrun_with_settings( fn to_application(app_call: &ApplicationCallTransaction, sender: &Address) -> Application { let params = ApplicationParams { - approval_program: app_call - .approval_program - .clone() - .map(|p| p.0) - .unwrap_or_default(), - clear_state_program: app_call - .clear_state_program - .clone() - .map(|p| p.0) - .unwrap_or_default(), - creator: *sender, - global_state: vec![], + approval_program: Bytes( + app_call + .approval_program + .clone() + .map(|p| p.0) + .unwrap_or_default(), + ), + clear_state_program: Bytes( + app_call + .clear_state_program + .clone() + .map(|p| p.0) + .unwrap_or_default(), + ), + creator: (*sender).to_string(), + global_state: Some(vec![]), global_state_schema: app_call .global_state_schema .clone() - .map(to_application_state_schema), + .map(to_application_state_schema) + .map(Box::new), local_state_schema: app_call .local_state_schema .clone() - .map(to_application_state_schema), + .map(to_application_state_schema) + .map(Box::new), + // TODO add this + extra_program_pages: None, }; Application { id: DEFAULT_APP_ID, - params, + params: Box::new(params), } } @@ -176,7 +185,7 @@ fn truncate(s: &str, max_len: usize) -> String { } } -fn stack_to_str(stack: &[TealValue], bytes_format: &BytesFormat) -> Result { +fn stack_to_str(stack: &[TealValue], bytes_format: &BytesFormat) -> Result { let mut elems = vec![]; for value in stack { match value.value_type { @@ -203,7 +212,7 @@ fn scratch_to_str( prev_scratch: &[TealValue], cur_scratch: &[TealValue], bytes_format: &BytesFormat, -) -> Result { +) -> Result { if cur_scratch.is_empty() { return Ok("".to_owned()); } @@ -235,7 +244,7 @@ fn trace( state: &[DryrunState], disassembly: &[String], config: &StackPrinterConfig, -) -> Result { +) -> Result { let mut lines = vec![vec![ "pc#".to_owned(), "ln#".to_owned(), @@ -254,7 +263,7 @@ fn trace( let cur_scratch = &s.scratch; let prev_scratch = if i > 0 { - state.to_owned().clone()[i - 1].clone().scratch + state[i - 1].clone().scratch.unwrap() } else { vec![] }; @@ -269,7 +278,11 @@ fn trace( format!("{:3}", s.line.to_string()), truncate(&src, config.max_column_widths.source), truncate( - &scratch_to_str(&prev_scratch, cur_scratch, &config.bytes_format)?, + &scratch_to_str( + &prev_scratch, + &cur_scratch.clone().unwrap()[..], + &config.bytes_format, + )?, config.max_column_widths.scratch, ), truncate( @@ -309,9 +322,9 @@ fn pad(s: &str, len: usize) -> String { format!("{s}{}", str::repeat(" ", len - s.len())) } -pub fn app_trace(dryrun_res: &DryrunTxnResult) -> Result { +pub fn app_trace(dryrun_res: &DryrunTxnResult) -> Result { trace( - &dryrun_res.app_call_trace, + &dryrun_res.app_call_trace.clone().unwrap(), &dryrun_res.disassembly, &StackPrinterConfig::default(), ) @@ -320,19 +333,27 @@ pub fn app_trace(dryrun_res: &DryrunTxnResult) -> Result { pub fn app_trace_with_config( dryrun_res: &DryrunTxnResult, config: &StackPrinterConfig, -) -> Result { - trace(&dryrun_res.app_call_trace, &dryrun_res.disassembly, config) +) -> Result { + trace( + &dryrun_res.app_call_trace.clone().unwrap(), + &dryrun_res.disassembly, + config, + ) } -pub fn lsig_trace(dryrun_res: &DryrunTxnResult) -> Result { +pub fn lsig_trace(dryrun_res: &DryrunTxnResult) -> Result { lsig_trace_with_config(dryrun_res, &StackPrinterConfig::default()) } pub fn lsig_trace_with_config( dryrun_res: &DryrunTxnResult, config: &StackPrinterConfig, -) -> Result { - trace(&dryrun_res.logic_sig_trace, &dryrun_res.disassembly, config) +) -> Result { + trace( + &dryrun_res.logic_sig_trace.clone().unwrap(), + &dryrun_res.disassembly, + config, + ) } fn to_hex_str(bytes: &[u8]) -> String { @@ -346,8 +367,8 @@ fn to_application_state_schema(schema: StateSchema) -> ApplicationStateSchema { } } -impl From for ServiceError { +impl From for Error { fn from(e: DecodeError) -> Self { - ServiceError::Msg(format!("Decoding error: {e}")) + Error::Msg(format!("Decoding error: {e}")) } } diff --git a/src/util/wait_for_pending_tx.rs b/src/util/wait_for_pending_tx.rs index 5f97c982..66b95cfd 100644 --- a/src/util/wait_for_pending_tx.rs +++ b/src/util/wait_for_pending_tx.rs @@ -1,5 +1,6 @@ use super::sleep; -use crate::{algod::v2::Algod, error::ServiceError, model::algod::v2::PendingTransaction}; +use crate::{algod::v2::Algod, Error}; +use algonaut_algod::models::PendingTransactionResponse; use instant::Instant; use std::time::Duration; @@ -7,16 +8,16 @@ use std::time::Duration; pub async fn wait_for_pending_transaction( algod: &Algod, tx_id: &str, -) -> Result { +) -> Result { let timeout = Duration::from_secs(60); let start = Instant::now(); loop { - let pending_transaction = algod.pending_transaction_with_id(tx_id).await?; + let pending_transaction = algod.pending_txn(tx_id).await?; // If the transaction has been confirmed or we time out, exit. if pending_transaction.confirmed_round.is_some() { return Ok(pending_transaction); } else if start.elapsed() >= timeout { - return Err(ServiceError::Msg(format!( + return Err(Error::Msg(format!( "Pending transaction timed out ({timeout:?})" ))); } diff --git a/test.env b/test.env index b182151b..df783a4f 100644 --- a/test.env +++ b/test.env @@ -13,37 +13,4 @@ REMOVE_LOCAL_FEATURES=0 # WARNING: Be careful when turning on the next variable. # In that case you'll need to provide all variables expected by `algorand-sdk-testing`'s `.env` -OVERWRITE_TESTING_ENVIRONMENT=1 - -# Used to determine sandbox build type: -TYPE="channel" # OR "source" - -# Used when TYPE==channel: -ALGOD_CHANNEL="nightly" - -# Used when TYPE==source: -ALGOD_URL="https://github.com/algorand/go-algorand" -ALGOD_BRANCH="master" -ALGOD_SHA="" - -# Used regardless of TYPE: -NETWORK_TEMPLATE="images/algod/DevModeNetwork.json" # refers to the ./images directory in the sandbox repo -NETWORK_NUM_ROUNDS=30000 -INDEXER_URL="https://github.com/algorand/indexer" -NODE_ARCHIVAL="False" -INDEXER_BRANCH="master" -INDEXER_SHA="cfdc471d0ba26aefb286584c11e2ae6d6fa08d05" - -# Sandbox configuration: -SANDBOX_URL="https://github.com/algorand/sandbox" -SANDBOX_BRANCH="master" -LOCAL_SANDBOX_DIR=".sandbox" - -# replacement values for Sandbox's docker-compose: -ALGOD_CONTAINER=sdk-harness-algod -KMD_PORT=60001 -ALGOD_PORT=60000 -INDEXER_CONTAINER=sdk-harness-indexer -INDEXER_PORT=59999 -POSTGRES_CONTAINER=sdk-harness-postgres -POSTGRES_PORT=65432 \ No newline at end of file +OVERWRITE_TESTING_ENVIRONMENT=0 diff --git a/tests/step_defs/integration/abi.rs b/tests/step_defs/integration/abi.rs index 6e325e78..ef2196bb 100644 --- a/tests/step_defs/integration/abi.rs +++ b/tests/step_defs/integration/abi.rs @@ -2,22 +2,18 @@ use crate::step_defs::{ integration::world::World, util::{read_teal, wait_for_pending_transaction}, }; -use algonaut::{ - atomic_transaction_composer::{ - transaction_signer::TransactionSigner, AbiArgValue, AbiMethodReturnValue, - AbiReturnDecodeError, AddMethodCallParams, AtomicTransactionComposer, - AtomicTransactionComposerStatus, TransactionWithSigner, - }, - error::ServiceError, +use algonaut::atomic_transaction_composer::{ + transaction_signer::TransactionSigner, AbiArgValue, AbiMethodReturnValue, AbiReturnDecodeError, + AddMethodCallParams, AtomicTransactionComposer, AtomicTransactionComposerStatus, + TransactionWithSigner, }; use algonaut_abi::{ abi_interactions::{AbiArgType, AbiMethod, AbiReturn, AbiReturnType, ReferenceArgType}, abi_type::{AbiType, AbiValue}, }; +use algonaut_algod::models::PendingTransactionResponse; use algonaut_core::{to_app_address, Address, MicroAlgos}; -use algonaut_model::algod::v2::PendingTransaction; use algonaut_transaction::{ - builder::TxnFee, transaction::{ApplicationCallOnComplete, StateSchema}, Pay, TxnBuilder, }; @@ -405,10 +401,7 @@ async fn add_method_call( app_id: application_id, method: abi_method.to_owned(), method_args: abi_method_args.to_owned(), - fee: TxnFee::Estimated { - fee_per_byte: tx_params.fee_per_byte, - min_fee: tx_params.min_fee, - }, + fee: MicroAlgos(tx_params.min_fee), sender: use_account.address(), suggested_params: tx_params, on_complete, @@ -469,7 +462,7 @@ fn i_build_the_transaction_group_with_the_composer(w: &mut World, error_type: St let message = match build_res { Ok(_) => None, Err(e) => match e { - ServiceError::Msg(m) => Some(m), + algonaut::Error::Msg(m) => Some(m), _ => None, }, }; @@ -702,7 +695,8 @@ async fn check_inner_txn_group_ids(w: &mut World, colon_separated_paths_string: let mut tx_infos_to_check = vec![]; for path in paths { - let mut current: PendingTransaction = tx_composer_res.method_results[0].tx_info.clone(); + let mut current: PendingTransactionResponse = + tx_composer_res.method_results[0].tx_info.clone(); for path_index in 1..path.len() { let inner_txn_index = path[path_index]; if path_index == 0 { @@ -710,7 +704,12 @@ async fn check_inner_txn_group_ids(w: &mut World, colon_separated_paths_string: .tx_info .clone(); } else { - current = current.inner_txs[inner_txn_index].clone(); + current = current + .inner_txns + .unwrap() + .get(inner_txn_index) + .unwrap() + .clone(); } } @@ -800,10 +799,7 @@ async fn i_fund_the_current_applications_address(w: &mut World, micro_algos: u64 let app_address = to_app_address(app_id); - let tx_params = algod - .suggested_transaction_params() - .await - .expect("couldn't get params"); + let tx_params = algod.txn_params().await.expect("couldn't get params"); let tx = TxnBuilder::with( &tx_params, @@ -818,7 +814,7 @@ async fn i_fund_the_current_applications_address(w: &mut World, micro_algos: u64 .expect("couldn't sign tx"); let res = algod - .broadcast_raw_transaction(&signed_tx.signed_transaction) + .send_raw_txn(&signed_tx.signed_transaction) .await .expect("couldn't send tx"); diff --git a/tests/step_defs/integration/applications.rs b/tests/step_defs/integration/applications.rs index d7442a32..5f3142d6 100644 --- a/tests/step_defs/integration/applications.rs +++ b/tests/step_defs/integration/applications.rs @@ -1,6 +1,6 @@ use crate::step_defs::integration::world::World; use crate::step_defs::util::{parse_app_args, read_teal, split_addresses, split_uint64}; -use algonaut_model::algod::v2::{Application, ApplicationLocalState}; +use algonaut_algod::models::{Application, ApplicationLocalState}; use algonaut_transaction::builder::{ CallApplication, ClearApplication, CloseApplication, DeleteApplication, OptInApplication, UpdateApplication, @@ -45,7 +45,7 @@ async fn i_build_an_application_transaction( let foreign_apps = split_uint64(&foreign_apps)?; let foreign_assets = split_uint64(&foreign_assets)?; - let params = algod.suggested_transaction_params().await?; + let params = algod.txn_params().await?; let tx_type = match operation.as_str() { "create" => { @@ -156,7 +156,7 @@ async fn i_remember_the_new_application_id(w: &mut World) { let tx_id = w.tx_id.as_ref().unwrap(); let app_ids: &mut Vec = w.app_ids.as_mut(); - let p_tx = algod.pending_transaction_with_id(tx_id).await.unwrap(); + let p_tx = algod.pending_txn(tx_id).await.unwrap(); assert!(p_tx.application_index.is_some()); let app_id = p_tx.application_index.unwrap(); @@ -181,17 +181,22 @@ async fn the_transient_account_should_have( let app_id = w.app_id.unwrap(); let account_infos = algod - .account_information(&transient_account.address()) + .account(&transient_account.address().to_string()) .await .unwrap(); - assert!(account_infos.apps_total_schema.is_some()); - let total_schema = account_infos.apps_total_schema.unwrap(); + assert!(account_infos.clone().apps_total_schema.is_some()); + let total_schema = account_infos.clone().apps_total_schema.unwrap(); assert_eq!(byte_slices, total_schema.num_byte_slice); assert_eq!(uints, total_schema.num_uint); - let app_in_account = account_infos.created_apps.iter().any(|a| a.id == app_id); + let app_in_account = account_infos + .clone() + .created_apps + .unwrap() + .iter() + .any(|a| a.id == app_id); match (app_created, app_in_account) { (true, false) => Err(format!("AppId {} is not found in the account", app_id))?, @@ -209,10 +214,12 @@ async fn the_transient_account_should_have( let key_values = match application_state.to_lowercase().as_ref() { "local" => { let local_state = account_infos + .clone() .apps_local_state - .iter() + .unwrap() + .into_iter() .filter(|s| s.id == app_id) - .collect::>(); + .collect::>(); let len = local_state.len(); if len == 1 { @@ -226,10 +233,12 @@ async fn the_transient_account_should_have( } "global" => { let apps = account_infos + .clone() .created_apps - .iter() + .unwrap() + .into_iter() .filter(|s| s.id == app_id) - .collect::>(); + .collect::>(); let len = apps.len(); if len == 1 { @@ -241,15 +250,15 @@ async fn the_transient_account_should_have( _ => Err(format!("Unknown application state: {}", application_state))?, }; - if key_values.is_empty() { + if key_values.is_none() { Err("Expected key values length to be greater than 0")? } let mut key_value_found = false; - for key_value in key_values.iter().filter(|kv| kv.key == key) { - if key_value.value.value_type == 1 { + for key_value in key_values.unwrap().iter().filter(|kv| kv.key == key) { + if (*key_value.value).value_type == 1 { let value_bytes = BASE64.decode(value.as_bytes())?; - if key_value.value.bytes != value_bytes { + if (*key_value.value).bytes != value_bytes { Err(format!( "Value mismatch (bytes): expected: '{:?}', got '{:?}'", value_bytes, key_value.value.bytes @@ -274,13 +283,3 @@ async fn the_transient_account_should_have( Ok(()) } - -// fn load_teal(file_name: &str) -> Result, Box> { -// Ok(fs::read(format!("tests/features/resources/{}", file_name))?) -// } - -// async fn load_and_compile_teal(algod: &Algod, file_name: &str) -> Result { -// let source = load_teal(file_name)?; - -// Ok(fs::read(format!("tests/features/resources/{}", file_name))?) -// } diff --git a/tests/step_defs/integration/general.rs b/tests/step_defs/integration/general.rs index 3ffdd45d..ac99cdfa 100644 --- a/tests/step_defs/integration/general.rs +++ b/tests/step_defs/integration/general.rs @@ -3,7 +3,7 @@ use crate::step_defs::{ util::{account_from_kmd_response, wait_for_pending_transaction}, }; use algonaut::{algod::v2::Algod, kmd::v1::Kmd}; -use algonaut_core::{MicroAlgos, Round}; +use algonaut_core::MicroAlgos; use algonaut_transaction::{Pay, TxnBuilder}; use cucumber::{given, then, when}; use rand::Rng; @@ -17,7 +17,7 @@ async fn an_algod_v2_client(w: &mut World) -> Result<(), Box> { ) .unwrap(); - algod.status_after_round(Round(1)).await?; + algod.status_after_block(1).await?; w.algod = Some(algod); Ok(()) @@ -75,7 +75,7 @@ async fn wallet_information(w: &mut World) -> Result<(), Box> { async fn suggested_params(w: &mut World) -> Result<(), Box> { let algod = w.algod.as_ref().unwrap(); - w.tx_params = Some(algod.suggested_transaction_params().await?); + w.tx_params = Some(algod.txn_params().await?); Ok(()) } @@ -100,7 +100,7 @@ async fn i_create_a_new_transient_account_and_fund_it_with_microalgos( let sender_account = account_from_kmd_response(&sender_key)?; - let params = algod.suggested_transaction_params().await?; + let params = algod.txn_params().await?; let tx = TxnBuilder::with( ¶ms, Pay::new( @@ -114,7 +114,7 @@ async fn i_create_a_new_transient_account_and_fund_it_with_microalgos( let s_tx = sender_account.sign_transaction(tx)?; - let send_response = algod.broadcast_signed_transaction(&s_tx).await?; + let send_response = algod.send_txn(&s_tx).await?; let _ = wait_for_pending_transaction(&algod, &send_response.tx_id); w.transient_account = Some(sender_account); @@ -141,7 +141,7 @@ async fn i_sign_and_submit_the_transaction_saving_the_tx_id_if_there_is_an_error let s_tx = transient_account.sign_transaction(tx.clone()).unwrap(); - match algod.broadcast_signed_transaction(&s_tx).await { + match algod.send_txn(&s_tx).await { Ok(response) => { w.tx_id = Some(response.tx_id); } diff --git a/tests/step_defs/integration/world.rs b/tests/step_defs/integration/world.rs index 7eb6279c..9d035791 100644 --- a/tests/step_defs/integration/world.rs +++ b/tests/step_defs/integration/world.rs @@ -7,7 +7,8 @@ use algonaut::{ kmd::v1::Kmd, }; use algonaut_abi::{abi_interactions::AbiMethod, abi_type::AbiType}; -use algonaut_core::{Address, SuggestedTransactionParams}; +use algonaut_algod::models::TransactionParams200Response; +use algonaut_core::Address; use algonaut_transaction::{account::Account, SignedTransaction, Transaction}; use cucumber; @@ -28,7 +29,7 @@ pub struct World { pub app_id: Option, pub app_ids: Vec, - pub tx_params: Option, + pub tx_params: Option, pub note: Option>, diff --git a/tests/step_defs/util.rs b/tests/step_defs/util.rs index 4204fd08..8cc463e5 100644 --- a/tests/step_defs/util.rs +++ b/tests/step_defs/util.rs @@ -6,20 +6,21 @@ use std::{ time::{Duration, Instant}, }; -use algonaut::{algod::v2::Algod, error::ServiceError}; +use algonaut::algod::v2::Algod; +use algonaut_algod::models::PendingTransactionResponse; use algonaut_core::{Address, CompiledTeal}; -use algonaut_model::{algod::v2::PendingTransaction, kmd::v1::ExportKeyResponse}; +use algonaut_model::kmd::v1::ExportKeyResponse; use algonaut_transaction::account::Account; /// Utility function to wait on a transaction to be confirmed pub async fn wait_for_pending_transaction( algod: &Algod, txid: &str, -) -> Result, ServiceError> { +) -> Result, algonaut::Error> { let timeout = Duration::from_secs(10); let start = Instant::now(); loop { - let pending_transaction = algod.pending_transaction_with_id(txid).await?; + let pending_transaction = algod.pending_txn(txid).await?; // If the transaction has been confirmed or we time out, exit. if pending_transaction.confirmed_round.is_some() { return Ok(Some(pending_transaction)); @@ -79,7 +80,7 @@ pub async fn read_teal(algod: &Algod, file_name: &str) -> CompiledTeal { let file_bytes = fs::read(&format!("tests/features/resources/{file_name}")).unwrap(); if file_name.ends_with(".teal") { - algod.compile_teal(&file_bytes).await.unwrap() + algod.teal_compile(&file_bytes, None).await.unwrap() } else { CompiledTeal(file_bytes) } diff --git a/tests/test_algod_v2.rs b/tests/test_algod_v2.rs deleted file mode 100644 index 4dde925a..00000000 --- a/tests/test_algod_v2.rs +++ /dev/null @@ -1,368 +0,0 @@ -use algonaut::algod::v2::Algod; -use algonaut_core::Round; -use algonaut_model::algod::v2::KeyRegistration; -use dotenv::dotenv; -use std::env; -use std::error::Error; -use tokio::test; - -#[test] -async fn test_genesis_endpoint() -> Result<(), Box> { - dotenv().ok(); - - let algod = Algod::new(&env::var("ALGOD_URL")?, &env::var("ALGOD_TOKEN")?)?; - - let res = algod.genesis().await; - - println!("{:#?}", res); - assert!(res.is_ok()); - - Ok(()) -} - -#[test] -async fn test_health_endpoint() -> Result<(), Box> { - dotenv().ok(); - - let algod = Algod::new(&env::var("ALGOD_URL")?, &env::var("ALGOD_TOKEN")?)?; - - let res = algod.health().await; - - println!("{:#?}", res); - assert!(res.is_ok()); - - Ok(()) -} - -#[test] -async fn test_metrics_endpoint() -> Result<(), Box> { - dotenv().ok(); - - let algod = Algod::new(&env::var("ALGOD_URL")?, &env::var("ALGOD_TOKEN")?)?; - - let res = algod.metrics().await; - - println!("{:#?}", res); - assert!(res.is_ok()); - - Ok(()) -} - -#[test] -async fn test_account_information_endpoint() -> Result<(), Box> { - dotenv().ok(); - - let algod = Algod::new(&env::var("ALGOD_URL")?, &env::var("ALGOD_TOKEN")?)?; - - let res = algod - .account_information(&"4MYUHDWHWXAKA5KA7U5PEN646VYUANBFXVJNONBK3TIMHEMWMD4UBOJBI4".parse()?) - .await; - - println!("{:#?}", res); - assert!(res.is_ok()); - - Ok(()) -} - -#[test] -async fn test_pending_transactions_for_endpoint() -> Result<(), Box> { - dotenv().ok(); - - let algod = Algod::new(&env::var("ALGOD_URL")?, &env::var("ALGOD_TOKEN")?)?; - - let res = algod - .pending_transactions_for( - &"4MYUHDWHWXAKA5KA7U5PEN646VYUANBFXVJNONBK3TIMHEMWMD4UBOJBI4".parse()?, - 0, - ) - .await; - - println!("{:#?}", res); - assert!(res.is_ok()); - - Ok(()) -} - -#[test] -#[ignore] -async fn test_application_information_endpoint() -> Result<(), Box> { - dotenv().ok(); - - let algod = Algod::new(&env::var("ALGOD_URL")?, &env::var("ALGOD_TOKEN")?)?; - - let res = algod.application_information(0).await; - - println!("{:#?}", res); - assert!(res.is_ok()); - - Ok(()) -} - -#[test] -#[ignore] -async fn test_asset_information_endpoint() -> Result<(), Box> { - dotenv().ok(); - - let algod = Algod::new(&env::var("ALGOD_URL")?, &env::var("ALGOD_TOKEN")?)?; - - let res = algod.asset_information(0).await; - - println!("{:#?}", res); - assert!(res.is_ok()); - - Ok(()) -} - -#[test] -#[ignore] -async fn test_block_endpoint() -> Result<(), Box> { - dotenv().ok(); - - let algod = Algod::new(&env::var("ALGOD_URL")?, &env::var("ALGOD_TOKEN")?)?; - - let last_round = algod.status().await?.last_round; - let res = algod.block(Round(last_round)).await; - - println!("{:#?}", res); - assert!(res.is_ok()); - - Ok(()) -} - -#[test] -#[ignore] -async fn test_start_catchup_endpoint() -> Result<(), Box> { - dotenv().ok(); - - let algod = Algod::new(&env::var("ALGOD_URL")?, &env::var("ALGOD_TOKEN")?)?; - - let res = algod - .start_catchup("4420000#Q7T2RRTDIRTYESIXKAAFJYFQWG4A3WRA3JIUZVCJ3F4AQ2G2HZRA") - .await; - - println!("{:#?}", res); - assert!(res.is_ok()); - - Ok(()) -} - -#[test] -#[ignore] -async fn test_abort_catchup_endpoint() -> Result<(), Box> { - dotenv().ok(); - - let algod = Algod::new(&env::var("ALGOD_URL")?, &env::var("ALGOD_TOKEN")?)?; - - let res = algod - .abort_catchup("4420000#Q7T2RRTDIRTYESIXKAAFJYFQWG4A3WRA3JIUZVCJ3F4AQ2G2HZRA") - .await; - - println!("{:#?}", res); - assert!(res.is_ok()); - - Ok(()) -} - -#[test] -async fn test_ledger_supply_endpoint() -> Result<(), Box> { - dotenv().ok(); - - let algod = Algod::new(&env::var("ALGOD_URL")?, &env::var("ALGOD_TOKEN")?)?; - - let res = algod.ledger_supply().await; - - println!("{:#?}", res); - assert!(res.is_ok()); - - Ok(()) -} - -#[test] -#[ignore] -async fn test_register_participation_keys_endpoint() -> Result<(), Box> { - dotenv().ok(); - - let algod = Algod::new(&env::var("ALGOD_URL")?, &env::var("ALGOD_TOKEN")?)?; - - let params = KeyRegistration { - fee: None, - key_dilution: None, - no_wait: None, - round_last_valid: None, - }; - - let address = env::var("ALICE_ADDRESS")?.parse()?; - - let res = algod.register_participation_keys(&address, ¶ms).await; - - println!("{:#?}", res); - assert!(res.is_ok()); - - Ok(()) -} - -#[test] -#[ignore] -async fn test_shutdown_endpoint() -> Result<(), Box> { - dotenv().ok(); - - let algod = Algod::new(&env::var("ALGOD_URL")?, &env::var("ALGOD_TOKEN")?)?; - - let res = algod.shutdown(0).await; - - println!("{:#?}", res); - assert!(res.is_ok()); - - Ok(()) -} - -#[test] -async fn test_status_endpoint() -> Result<(), Box> { - dotenv().ok(); - - let algod = Algod::new(&env::var("ALGOD_URL")?, &env::var("ALGOD_TOKEN")?)?; - - let res = algod.status().await; - - println!("{:#?}", res); - assert!(res.is_ok()); - - Ok(()) -} - -#[test] -async fn test_status_after_round_endpoint() -> Result<(), Box> { - dotenv().ok(); - - let algod = Algod::new(&env::var("ALGOD_URL")?, &env::var("ALGOD_TOKEN")?)?; - - let node_status = algod.status().await?; - - let res = algod - .status_after_round(Round(node_status.last_round + 2)) - .await; - - println!("{:#?}", res); - assert!(res.is_ok()); - - Ok(()) -} - -#[test] -async fn test_compile_teal_endpoint() -> Result<(), Box> { - dotenv().ok(); - - let algod = Algod::new(&env::var("ALGOD_URL")?, &env::var("ALGOD_TOKEN")?)?; - - let res = algod - .compile_teal( - r#" -int 1 -bnz safe -err -safe: -pop -"# - .as_bytes(), - ) - .await; - - println!("{:#?}", res); - assert!(res.is_ok()); - - Ok(()) -} - -#[test] -async fn test_failure_compiling_teal() -> Result<(), Box> { - dotenv().ok(); - - let algod = Algod::new(&env::var("ALGOD_URL")?, &env::var("ALGOD_TOKEN")?)?; - - let res = algod.compile_teal("not-a-teal-program".as_bytes()).await; - - println!("{:#?}", res); - assert!(res.is_err()); - - Ok(()) -} - -#[test] -#[ignore = "TODO"] -async fn test_dryrun_teal_endpoint() -> Result<(), Box> { - dotenv().ok(); - - Ok(()) -} - -#[test] -#[ignore = "TODO"] -async fn test_broadcast_raw_transaction_endpoint() -> Result<(), Box> { - dotenv().ok(); - - let algod = Algod::new(&env::var("ALGOD_URL")?, &env::var("ALGOD_TOKEN")?)?; - - let res = algod.broadcast_raw_transaction(&[0; 32]).await; - - println!("{:#?}", res); - assert!(res.is_ok()); - - Ok(()) -} - -#[test] -async fn test_transaction_params_endpoint() -> Result<(), Box> { - dotenv().ok(); - - let algod = Algod::new(&env::var("ALGOD_URL")?, &env::var("ALGOD_TOKEN")?)?; - - let res = algod.transaction_params().await; - - println!("{:#?}", res); - assert!(res.is_ok()); - - Ok(()) -} - -#[test] -async fn test_pending_transactions_endpoint() -> Result<(), Box> { - dotenv().ok(); - - let algod = Algod::new(&env::var("ALGOD_URL")?, &env::var("ALGOD_TOKEN")?)?; - - let res = algod.pending_transactions(0).await; - - println!("{:#?}", res); - assert!(res.is_ok()); - - Ok(()) -} - -#[test] -#[ignore] -async fn test_pending_transaction_with_id_endpoint() -> Result<(), Box> { - dotenv().ok(); - - let algod = Algod::new(&env::var("ALGOD_URL")?, &env::var("ALGOD_TOKEN")?)?; - - let res = algod.pending_transaction_with_id("").await; - - println!("{:#?}", res); - assert!(res.is_ok()); - - Ok(()) -} - -#[test] -async fn test_versions_endpoint() -> Result<(), Box> { - dotenv().ok(); - - let algod = Algod::new(&env::var("ALGOD_URL")?, &env::var("ALGOD_TOKEN")?)?; - - let res = algod.versions().await; - - println!("{:#?}", res); - assert!(res.is_ok()); - - Ok(()) -} diff --git a/tests/test_indexer_v2.rs b/tests/test_indexer_v2.rs deleted file mode 100644 index dff9d32e..00000000 --- a/tests/test_indexer_v2.rs +++ /dev/null @@ -1,305 +0,0 @@ -use algonaut::indexer::v2::Indexer; -use algonaut_core::Round; -use algonaut_model::indexer::v2::{ - QueryAccount, QueryAccountInfo, QueryAccountTransaction, QueryApplicationInfo, - QueryApplications, QueryAssetTransaction, QueryAssets, QueryAssetsInfo, QueryBalances, - QueryTransaction, Role, -}; -use dotenv::dotenv; -use std::env; -use std::error::Error; -use tokio::test; - -#[test] -async fn test_health_endpoint() -> Result<(), Box> { - dotenv().ok(); - - let indexer = Indexer::new(&env::var("INDEXER_URL")?)?; - - let res = indexer.health().await; - - println!("{:#?}", res); - assert!(res.is_ok()); - - Ok(()) -} - -#[test] -async fn test_accounts_endpoint() -> Result<(), Box> { - dotenv().ok(); - - let indexer = Indexer::new(&env::var("INDEXER_URL")?)?; - - let query = QueryAccount { - application_id: None, - asset_id: None, - auth_addr: None, - currency_greater_than: None, - currency_less_than: None, - limit: Some(2), - next: None, - round: None, - }; - - let res = indexer.accounts(&query).await; - - println!("{:#?}", res); - assert!(res.is_ok()); - - Ok(()) -} - -#[test] -async fn test_account_info_endpoint() -> Result<(), Box> { - dotenv().ok(); - - let indexer = Indexer::new(&env::var("INDEXER_URL")?)?; - - let address = env::var("ALICE_ADDRESS")?.parse()?; - - let query = QueryAccountInfo { - include_all: None, - round: Some(Round(0)), - }; - - let res = indexer.account_info(&address, &query).await; - - println!("{:#?}", res); - assert!(res.is_ok()); - - Ok(()) -} - -#[test] -async fn test_account_transactions_endpoint() -> Result<(), Box> { - dotenv().ok(); - - let indexer = Indexer::new(&env::var("INDEXER_URL")?)?; - - let query = QueryAccountTransaction { - application_id: None, - after_time: None, - asset_id: None, - before_time: None, - currency_greater_than: None, - currency_less_than: None, - limit: None, - max_round: None, - min_round: None, - next: None, - note_prefix: None, - rekey_to: None, - round: None, - sig_type: None, - tx_type: None, - txid: None, - }; - - let address = env::var("ALICE_ADDRESS")?.parse()?; - - let res = indexer.account_transactions(&address, &query).await; - - println!("{:#?}", res); - assert!(res.is_ok()); - - Ok(()) -} - -#[test] -async fn test_applications_endpoint() -> Result<(), Box> { - dotenv().ok(); - - let indexer = Indexer::new(&env::var("INDEXER_URL")?)?; - - let query = QueryApplications { - application_id: None, - limit: None, - next: None, - }; - - let res = indexer.applications(&query).await; - - println!("{:#?}", res); - assert!(res.is_ok()); - - Ok(()) -} - -#[test] -#[ignore] -async fn test_applications_info_endpoint() -> Result<(), Box> { - dotenv().ok(); - - let indexer = Indexer::new(&env::var("INDEXER_URL")?)?; - - let query = QueryApplicationInfo { include_all: None }; - - let res = indexer.application_info(123, &query).await; - - println!("{:#?}", res); - assert!(res.is_ok()); - - Ok(()) -} - -#[test] -async fn test_assets_endpoint() -> Result<(), Box> { - dotenv().ok(); - - let indexer = Indexer::new(&env::var("INDEXER_URL")?)?; - - let query = QueryAssets { - asset_id: None, - creator: None, - limit: None, - name: None, - next: None, - unit: None, - }; - - let res = indexer.assets(&query).await; - - println!("{:#?}", res); - assert!(res.is_ok()); - - Ok(()) -} - -#[test] -#[ignore] -async fn test_assets_info_endpoint() -> Result<(), Box> { - dotenv().ok(); - - let indexer = Indexer::new(&env::var("INDEXER_URL")?)?; - - let query = QueryAssetsInfo { include_all: None }; - - let res = indexer.assets_info(123, &query).await; - - println!("{:#?}", res); - assert!(res.is_ok()); - - Ok(()) -} - -#[test] -async fn test_asset_balances_endpoint() -> Result<(), Box> { - dotenv().ok(); - - let indexer = Indexer::new(&env::var("INDEXER_URL")?)?; - - let query = QueryBalances { - currency_greater_than: None, - currency_less_than: None, - limit: None, - next: None, - round: None, - }; - - let res = indexer.asset_balances(123, &query).await; - - println!("{:#?}", res); - assert!(res.is_ok()); - - Ok(()) -} - -#[test] -async fn test_asset_transactions_endpoint() -> Result<(), Box> { - dotenv().ok(); - - let indexer = Indexer::new(&env::var("INDEXER_URL")?)?; - - let query = QueryAssetTransaction { - address: None, - address_role: Some(Role::Sender), - after_time: None, - before_time: None, - currency_greater_than: None, - currency_less_than: None, - exclude_close_to: None, - limit: None, - max_round: None, - min_round: None, - next: None, - note_prefix: None, - rekey_to: None, - round: None, - sig_type: None, - tx_type: None, - txid: None, - }; - - let res = indexer.asset_transactions(123, &query).await; - - println!("{:#?}", res); - assert!(res.is_ok()); - - Ok(()) -} - -#[test] -async fn test_block_endpoint() -> Result<(), Box> { - dotenv().ok(); - - let indexer = Indexer::new(&env::var("INDEXER_URL")?)?; - - let res = indexer.block(Round(0)).await; - - println!("{:#?}", res); - assert!(res.is_ok()); - - Ok(()) -} - -#[test] -#[ignore] -async fn test_transactions_endpoint() -> Result<(), Box> { - dotenv().ok(); - - let indexer = Indexer::new(&env::var("INDEXER_URL")?)?; - - let query = QueryTransaction { - address: None, - address_role: None, - after_time: None, - application_id: None, - asset_id: None, - before_time: None, - currency_greater_than: None, - currency_less_than: None, - exclude_close_to: None, - limit: None, - max_round: None, - min_round: None, - next: None, - note_prefix: None, - rekey_to: None, - round: None, - sig_type: None, - tx_type: None, - txid: None, - }; - - let res = indexer.transactions(&query).await; - - println!("{:#?}", res); - assert!(res.is_ok()); - - Ok(()) -} - -#[test] -#[ignore] -async fn test_transaction_info_endpoint() -> Result<(), Box> { - dotenv().ok(); - - let indexer = Indexer::new(&env::var("INDEXER_URL")?)?; - - let res = indexer.transaction_info("123").await; - - println!("{:#?}", res); - assert!(res.is_ok()); - - Ok(()) -} diff --git a/tests/test_kmd_v1.rs b/tests/test_kmd_v1.rs deleted file mode 100644 index 9ac0c5ef..00000000 --- a/tests/test_kmd_v1.rs +++ /dev/null @@ -1,679 +0,0 @@ -use algonaut::kmd::v1::Kmd; -use algonaut_crypto::{Ed25519PublicKey, MasterDerivationKey}; -use dotenv::dotenv; -use rand::{distributions::Alphanumeric, Rng}; -use std::env; -use std::error::Error; -use tokio::test; - -#[test] -async fn test_versions_endpoint() -> Result<(), Box> { - dotenv().ok(); - - let kmd = Kmd::new(&env::var("KMD_URL")?, &env::var("KMD_TOKEN")?)?; - - let versions = kmd.versions().await; - println!("{:#?}", versions); - assert!(versions.is_ok()); - - Ok(()) -} - -#[test] -async fn test_list_wallets_endpoint() -> Result<(), Box> { - dotenv().ok(); - - let kmd = Kmd::new(&env::var("KMD_URL")?, &env::var("KMD_TOKEN")?)?; - - let wallets = kmd.list_wallets().await; - println!("{:#?}", wallets); - assert!(wallets.is_ok()); - - Ok(()) -} - -#[test] -async fn test_create_wallet_and_obtain_handle() -> Result<(), Box> { - dotenv().ok(); - - let kmd = Kmd::new(&env::var("KMD_URL")?, &env::var("KMD_TOKEN")?)?; - - let wallet_name: String = rand::thread_rng() - .sample_iter(&Alphanumeric) - .take(7) - .map(char::from) - .collect(); - - let wallet = kmd - .create_wallet( - wallet_name.as_ref(), - "testpassword", - "sqlite", - MasterDerivationKey([0; 32]), - ) - .await; - - println!("{:#?}", wallet); - assert!(wallet.is_ok()); - - let wallet = wallet.unwrap(); - - let id = wallet.wallet.id.as_ref(); - let handle = kmd.init_wallet_handle(id, "testpassword").await; - - println!("{:#?}", handle); - assert!(handle.is_ok()); - - Ok(()) -} - -#[test] -async fn test_release_wallet_handle_endpoint() -> Result<(), Box> { - dotenv().ok(); - - let kmd = Kmd::new(&env::var("KMD_URL")?, &env::var("KMD_TOKEN")?)?; - - let wallet_name: String = rand::thread_rng() - .sample_iter(&Alphanumeric) - .take(7) - .map(char::from) - .collect(); - - let wallet = kmd - .create_wallet( - wallet_name.as_ref(), - "testpassword", - "sqlite", - MasterDerivationKey([0; 32]), - ) - .await; - println!("{:#?}", wallet); - assert!(wallet.is_ok()); - - let wallet = wallet.unwrap(); - - let id = wallet.wallet.id.as_ref(); - let handle = kmd.init_wallet_handle(id, "testpassword").await; - - println!("{:#?}", handle); - assert!(handle.is_ok()); - - let res = kmd - .release_wallet_handle(handle.unwrap().wallet_handle_token.as_ref()) - .await; - - println!("{:#?}", res); - assert!(res.is_ok()); - - Ok(()) -} - -#[test] -async fn test_renew_wallet_handle_endpoint() -> Result<(), Box> { - dotenv().ok(); - - let kmd = Kmd::new(&env::var("KMD_URL")?, &env::var("KMD_TOKEN")?)?; - - let wallet_name: String = rand::thread_rng() - .sample_iter(&Alphanumeric) - .take(7) - .map(char::from) - .collect(); - - let wallet = kmd - .create_wallet( - wallet_name.as_ref(), - "testpassword", - "sqlite", - MasterDerivationKey([0; 32]), - ) - .await; - println!("{:#?}", wallet); - assert!(wallet.is_ok()); - - let wallet = wallet.unwrap(); - - let id = wallet.wallet.id.as_ref(); - let handle = kmd.init_wallet_handle(id, "testpassword").await; - - println!("{:#?}", handle); - assert!(handle.is_ok()); - - let res = kmd - .renew_wallet_handle(handle.unwrap().wallet_handle_token.as_ref()) - .await; - - println!("{:#?}", res); - assert!(res.is_ok()); - - Ok(()) -} - -#[test] -async fn test_rename_wallet_endpoint() -> Result<(), Box> { - dotenv().ok(); - - let kmd = Kmd::new(&env::var("KMD_URL")?, &env::var("KMD_TOKEN")?)?; - - let wallet_name: String = rand::thread_rng() - .sample_iter(&Alphanumeric) - .take(7) - .map(char::from) - .collect(); - - let wallet = kmd - .create_wallet( - wallet_name.as_ref(), - "testpassword", - "sqlite", - MasterDerivationKey([0; 32]), - ) - .await; - println!("{:#?}", wallet); - assert!(wallet.is_ok()); - - let new_name: String = rand::thread_rng() - .sample_iter(&Alphanumeric) - .take(7) - .map(char::from) - .collect(); - - let res = kmd - .rename_wallet( - wallet.unwrap().wallet.id.as_ref(), - "testpassword", - new_name.as_ref(), - ) - .await; - - println!("{:#?}", res); - assert!(res.is_ok()); - - Ok(()) -} - -#[test] -async fn test_get_wallet_info_endpoint() -> Result<(), Box> { - dotenv().ok(); - - let kmd = Kmd::new(&env::var("KMD_URL")?, &env::var("KMD_TOKEN")?)?; - - let wallet_name: String = rand::thread_rng() - .sample_iter(&Alphanumeric) - .take(7) - .map(char::from) - .collect(); - - let wallet = kmd - .create_wallet( - wallet_name.as_ref(), - "testpassword", - "sqlite", - MasterDerivationKey([0; 32]), - ) - .await; - println!("{:#?}", wallet); - assert!(wallet.is_ok()); - - let wallet = wallet.unwrap(); - - let id = wallet.wallet.id.as_ref(); - let handle = kmd.init_wallet_handle(id, "testpassword").await; - - println!("{:#?}", handle); - assert!(handle.is_ok()); - - let res = kmd - .get_wallet_info(handle.unwrap().wallet_handle_token.as_ref()) - .await; - - println!("{:#?}", res); - assert!(res.is_ok()); - - Ok(()) -} - -#[test] -async fn test_export_wallet_endpoint() -> Result<(), Box> { - dotenv().ok(); - - let kmd = Kmd::new(&env::var("KMD_URL")?, &env::var("KMD_TOKEN")?)?; - - let wallet_name: String = rand::thread_rng() - .sample_iter(&Alphanumeric) - .take(7) - .map(char::from) - .collect(); - - let wallet = kmd - .create_wallet( - wallet_name.as_ref(), - "testpassword", - "sqlite", - MasterDerivationKey([0; 32]), - ) - .await; - println!("{:#?}", wallet); - assert!(wallet.is_ok()); - - let wallet = wallet.unwrap(); - - let id = wallet.wallet.id.as_ref(); - let handle = kmd.init_wallet_handle(id, "testpassword").await; - - println!("{:#?}", handle); - assert!(handle.is_ok()); - - let res = kmd - .export_master_derivation_key(handle.unwrap().wallet_handle_token.as_ref(), "testpassword") - .await; - - println!("{:#?}", res); - assert!(res.is_ok()); - - Ok(()) -} - -#[test] -async fn test_import_export_key() -> Result<(), Box> { - dotenv().ok(); - - let kmd = Kmd::new(&env::var("KMD_URL")?, &env::var("KMD_TOKEN")?)?; - - let wallet_name: String = rand::thread_rng() - .sample_iter(&Alphanumeric) - .take(7) - .map(char::from) - .collect(); - - let wallet = kmd - .create_wallet( - wallet_name.as_ref(), - "testpassword", - "sqlite", - MasterDerivationKey([0; 32]), - ) - .await; - println!("{:#?}", wallet); - assert!(wallet.is_ok()); - - let wallet = wallet.unwrap(); - - let id = wallet.wallet.id.as_ref(); - let handle = kmd.init_wallet_handle(id, "testpassword").await; - - println!("{:#?}", handle); - assert!(handle.is_ok()); - - let handle = handle.unwrap(); - - let key = kmd - .import_key(handle.wallet_handle_token.as_ref(), [0; 32]) - .await; - - println!("{:#?}", key); - assert!(key.is_ok()); - - let key = key.unwrap(); - - let res = kmd - .export_key( - handle.wallet_handle_token.as_ref(), - "testpassword", - &key.address.parse()?, - ) - .await; - - println!("{:#?}", res); - assert!(res.is_ok()); - - Ok(()) -} - -#[test] -async fn test_generate_key_endpoint() -> Result<(), Box> { - dotenv().ok(); - - let kmd = Kmd::new(&env::var("KMD_URL")?, &env::var("KMD_TOKEN")?)?; - - let wallet_name: String = rand::thread_rng() - .sample_iter(&Alphanumeric) - .take(7) - .map(char::from) - .collect(); - - let wallet = kmd - .create_wallet( - wallet_name.as_ref(), - "testpassword", - "sqlite", - MasterDerivationKey([0; 32]), - ) - .await; - println!("{:#?}", wallet); - assert!(wallet.is_ok()); - - let wallet = wallet.unwrap(); - - let id = wallet.wallet.id.as_ref(); - let handle = kmd.init_wallet_handle(id, "testpassword").await; - - println!("{:#?}", handle); - assert!(handle.is_ok()); - - let res = kmd - .generate_key(handle.unwrap().wallet_handle_token.as_ref()) - .await; - - println!("{:#?}", res); - assert!(res.is_ok()); - - Ok(()) -} - -#[test] -async fn test_delete_key_endpoint() -> Result<(), Box> { - dotenv().ok(); - - let kmd = Kmd::new(&env::var("KMD_URL")?, &env::var("KMD_TOKEN")?)?; - - let wallet_name: String = rand::thread_rng() - .sample_iter(&Alphanumeric) - .take(7) - .map(char::from) - .collect(); - - let wallet = kmd - .create_wallet( - wallet_name.as_ref(), - "testpassword", - "sqlite", - MasterDerivationKey([0; 32]), - ) - .await; - println!("{:#?}", wallet); - assert!(wallet.is_ok()); - - let wallet = wallet.unwrap(); - - let id = wallet.wallet.id.as_ref(); - let handle = kmd.init_wallet_handle(id, "testpassword").await; - - println!("{:#?}", handle); - assert!(handle.is_ok()); - - let handle = handle.unwrap(); - - let key = kmd.generate_key(handle.wallet_handle_token.as_ref()).await; - - println!("{:#?}", key); - assert!(key.is_ok()); - - let key = key.unwrap(); - - let res = kmd - .delete_key( - handle.wallet_handle_token.as_ref(), - "testpassword", - key.address.as_ref(), - ) - .await; - - println!("{:#?}", res); - assert!(res.is_ok()); - - Ok(()) -} - -#[test] -async fn test_list_keys_endpoint() -> Result<(), Box> { - dotenv().ok(); - - let kmd = Kmd::new(&env::var("KMD_URL")?, &env::var("KMD_TOKEN")?)?; - - let wallet_name: String = rand::thread_rng() - .sample_iter(&Alphanumeric) - .take(7) - .map(char::from) - .collect(); - - let wallet = kmd - .create_wallet( - wallet_name.as_ref(), - "testpassword", - "sqlite", - MasterDerivationKey([0; 32]), - ) - .await; - println!("{:#?}", wallet); - assert!(wallet.is_ok()); - - let wallet = wallet.unwrap(); - - let id = wallet.wallet.id.as_ref(); - let handle = kmd.init_wallet_handle(id, "testpassword").await; - - println!("{:#?}", handle); - assert!(handle.is_ok()); - - let handle = handle.unwrap(); - - let res = kmd.generate_key(handle.wallet_handle_token.as_ref()).await; - - println!("{:#?}", res); - assert!(res.is_ok()); - - let res = kmd.list_keys(handle.wallet_handle_token.as_ref()).await; - - println!("{:#?}", res); - assert!(res.is_ok()); - - Ok(()) -} - -#[test] -async fn test_list_keys_of_empty_wallet() -> Result<(), Box> { - dotenv().ok(); - - let kmd = Kmd::new(&env::var("KMD_URL")?, &env::var("KMD_TOKEN")?)?; - - let wallet_name: String = rand::thread_rng() - .sample_iter(&Alphanumeric) - .take(7) - .map(char::from) - .collect(); - - let wallet = kmd - .create_wallet( - wallet_name.as_ref(), - "testpassword", - "sqlite", - MasterDerivationKey([0; 32]), - ) - .await; - println!("{:#?}", wallet); - assert!(wallet.is_ok()); - - let wallet = wallet.unwrap(); - - let id = wallet.wallet.id.as_ref(); - let handle = kmd.init_wallet_handle(id, "testpassword").await; - - println!("{:#?}", handle); - assert!(handle.is_ok()); - - let res = kmd - .list_keys(handle.unwrap().wallet_handle_token.as_ref()) - .await; - - println!("{:#?}", res); - assert!(res.is_ok()); - - Ok(()) -} - -#[test] -async fn test_list_multisig_endpoint() -> Result<(), Box> { - dotenv().ok(); - - let kmd = Kmd::new(&env::var("KMD_URL")?, &env::var("KMD_TOKEN")?)?; - - let wallet_name: String = rand::thread_rng() - .sample_iter(&Alphanumeric) - .take(7) - .map(char::from) - .collect(); - - let wallet = kmd - .create_wallet( - wallet_name.as_ref(), - "testpassword", - "sqlite", - MasterDerivationKey([0; 32]), - ) - .await; - println!("{:#?}", wallet); - assert!(wallet.is_ok()); - - let wallet = wallet.unwrap(); - - let id = wallet.wallet.id.as_ref(); - let handle = kmd.init_wallet_handle(id, "testpassword").await; - - println!("{:#?}", handle); - assert!(handle.is_ok()); - - let res = kmd - .list_multisig(handle.unwrap().wallet_handle_token.as_ref()) - .await; - - println!("{:#?}", res); - assert!(res.is_ok()); - - Ok(()) -} - -#[test] -async fn test_import_export_multisig() -> Result<(), Box> { - dotenv().ok(); - - let kmd = Kmd::new(&env::var("KMD_URL")?, &env::var("KMD_TOKEN")?)?; - - let version = 1; - let threshold = 1; - let pks = [Ed25519PublicKey([0; 32]), Ed25519PublicKey([1; 32])]; - - let wallet_name: String = rand::thread_rng() - .sample_iter(&Alphanumeric) - .take(7) - .map(char::from) - .collect(); - - let wallet = kmd - .create_wallet( - wallet_name.as_ref(), - "testpassword", - "sqlite", - MasterDerivationKey([0; 32]), - ) - .await; - println!("{:#?}", wallet); - assert!(wallet.is_ok()); - - let wallet = wallet.unwrap(); - - let id = wallet.wallet.id.as_ref(); - let handle = kmd.init_wallet_handle(id, "testpassword").await; - - println!("{:#?}", handle); - assert!(handle.is_ok()); - - let handle = handle.unwrap(); - - let multisig = kmd - .import_multisig( - handle.wallet_handle_token.as_ref(), - version, - threshold, - &pks, - ) - .await; - - println!("{:#?}", multisig); - assert!(multisig.is_ok()); - - let res = kmd - .export_multisig( - handle.wallet_handle_token.as_ref(), - multisig.unwrap().address.as_ref(), - ) - .await; - - println!("{:#?}", res); - assert!(res.is_ok()); - - Ok(()) -} - -#[test] -async fn test_delete_multisig_endpoint() -> Result<(), Box> { - dotenv().ok(); - - let kmd = Kmd::new(&env::var("KMD_URL")?, &env::var("KMD_TOKEN")?)?; - - let version = 1; - let threshold = 1; - let pks = [Ed25519PublicKey([0; 32]), Ed25519PublicKey([1; 32])]; - - let wallet_name: String = rand::thread_rng() - .sample_iter(&Alphanumeric) - .take(7) - .map(char::from) - .collect(); - - let wallet = kmd - .create_wallet( - wallet_name.as_ref(), - "testpassword", - "sqlite", - MasterDerivationKey([0; 32]), - ) - .await; - println!("{:#?}", wallet); - assert!(wallet.is_ok()); - - let wallet = wallet.unwrap(); - - let id = wallet.wallet.id.as_ref(); - let handle = kmd.init_wallet_handle(id, "testpassword").await; - - println!("{:#?}", handle); - assert!(handle.is_ok()); - - let handle = handle.unwrap(); - - let multisig = kmd - .import_multisig( - handle.wallet_handle_token.as_ref(), - version, - threshold, - &pks, - ) - .await; - - println!("{:#?}", multisig); - assert!(multisig.is_ok()); - - let res = kmd - .delete_multisig( - handle.wallet_handle_token.as_ref(), - "testpassword", - multisig.unwrap().address.as_ref(), - ) - .await; - - println!("{:#?}", res); - assert!(res.is_ok()); - - Ok(()) -} diff --git a/tests/test_transactions.rs b/tests/test_transactions.rs deleted file mode 100644 index ea0c4bed..00000000 --- a/tests/test_transactions.rs +++ /dev/null @@ -1,137 +0,0 @@ -use algonaut::algod::v2::Algod; -use algonaut_core::Address; -use algonaut_transaction::account::Account; -use algonaut_transaction::transaction::StateSchema; -use algonaut_transaction::CreateApplication; -use algonaut_transaction::TxnBuilder; -use dotenv::dotenv; -use std::env; -use std::error::Error; -use tokio::test; - -#[test] -async fn test_pending_transactions_endpoint() -> Result<(), Box> { - dotenv().ok(); - - let algod = Algod::new(&env::var("ALGOD_URL")?, &env::var("ALGOD_TOKEN")?)?; - - println!("{:?}", algod.pending_transactions(0).await); - assert!(algod.pending_transactions(0).await.is_ok()); - - Ok(()) -} - -#[test] -async fn test_transaction_information_endpoint() -> Result<(), Box> { - dotenv().ok(); - - let algod = Algod::new(&env::var("ALGOD_URL")?, &env::var("ALGOD_TOKEN")?)?; - - println!("{:?}", algod.transaction_params().await); - assert!(algod.transaction_params().await.is_ok()); - - Ok(()) -} - -// Preconditions: import and fund sender account -#[test] -async fn test_app_call_parameters() -> Result<(), Box> { - dotenv().ok(); - - let algod = Algod::new(&env::var("ALGOD_URL")?, &env::var("ALGOD_TOKEN")?)?; - - let sender = Account::from_mnemonic("auction inquiry lava second expand liberty glass involve ginger illness length room item discover ahead table doctor term tackle cement bonus profit right above catch")?; - dbg!(algod.account_information(&sender.address()).await?); - - let approval_program = r#" -#pragma version 4 -txna ApplicationArgs 0 -byte 0x0100FF -== -txna ApplicationArgs 1 -btoi -int 18446744073709551615 -== -&& -txna ApplicationArgs 2 -addr MKRBTLNZRS3UZZDS5OWPLP7YPHUDNKXFUFN5PNCJ3P2XRG74HNOGY6XOYQ -== -&& -txna ApplicationArgs 3 -byte b64 aGVsbG8= -== -&& -txna Accounts 1 -addr BKO5VOVEPG7TXAF5YYJHPMRADP2FQ3MGXEZG5BQEBJ2BF76IGFSO5M7PLE -== -&& -txna Accounts 2 -addr OEZKCDB3GLVZ5BJ7BNFS2IU7XL5TQ5E4QMRKODM3EM6JODWWSYV4FECJRY -== -&& -txna Applications 1 -int 1 -== -&& -txna Applications 2 -int 2 -== -&& -txna Assets 0 -int 1234 -== -&& -"# - .as_bytes(); - - let clear_program = r#" -#pragma version 4 -int 1 -"# - .as_bytes(); - - let compiled_approval_program = algod.compile_teal(&approval_program).await?; - let compiled_clear_program = algod.compile_teal(&clear_program).await?; - - let params = algod.suggested_transaction_params().await?; - let t = TxnBuilder::with( - ¶ms, - CreateApplication::new( - sender.address(), - compiled_approval_program.clone(), - compiled_clear_program, - StateSchema { - number_ints: 0, - number_byteslices: 0, - }, - StateSchema { - number_ints: 0, - number_byteslices: 0, - }, - ) - .app_arguments(vec![ - vec![1, 0, 255], // bytes (directly) - u64::MAX.to_be_bytes().to_vec(), // u64 - "MKRBTLNZRS3UZZDS5OWPLP7YPHUDNKXFUFN5PNCJ3P2XRG74HNOGY6XOYQ" - .parse::
()? - .0 - .to_vec(), // address - "hello".as_bytes().to_vec(), // string - ]) - .accounts(vec![ - "BKO5VOVEPG7TXAF5YYJHPMRADP2FQ3MGXEZG5BQEBJ2BF76IGFSO5M7PLE".parse()?, - "OEZKCDB3GLVZ5BJ7BNFS2IU7XL5TQ5E4QMRKODM3EM6JODWWSYV4FECJRY".parse()?, - ]) - .foreign_apps(vec![1, 2]) - .foreign_assets(vec![1234]) - .build(), - ) - .build()?; - - let signed_t = sender.sign_transaction(t)?; - - let send_response = algod.broadcast_signed_transaction(&signed_t).await?; - println!("send_response: {:?}", send_response); - - Ok(()) -}