diff --git a/apps/DataAggregator/Controllers/RootController.cs b/apps/DataAggregator/Controllers/RootController.cs index e5d6e82b3..905fbaae1 100644 --- a/apps/DataAggregator/Controllers/RootController.cs +++ b/apps/DataAggregator/Controllers/RootController.cs @@ -88,6 +88,7 @@ public JsonResult GetRootResponse() docs = "https://docs.radixdlt.com", repo = "https://github.com/radixdlt/babylon-gateway", ledger_commit_health = healthReport, - }) { StatusCode = healthReport.IsHealthy ? 200 : 500 }; + }) + { StatusCode = healthReport.IsHealthy ? 200 : 500 }; } } diff --git a/apps/GatewayApi/ExceptionHandlingMiddleware/ExceptionHandlingMiddleware.cs b/apps/GatewayApi/ExceptionHandlingMiddleware/ExceptionHandlingMiddleware.cs index 44657ae73..a635096f0 100644 --- a/apps/GatewayApi/ExceptionHandlingMiddleware/ExceptionHandlingMiddleware.cs +++ b/apps/GatewayApi/ExceptionHandlingMiddleware/ExceptionHandlingMiddleware.cs @@ -129,7 +129,7 @@ private KnownGatewayErrorException HandleException(HttpContext httpContext, Exce { switch (exception) { - case BadHttpRequestException badHttpRequestException : + case BadHttpRequestException badHttpRequestException: _logger.LogWarning(exception, "Bad http request. [RequestTrace={TraceId}]", traceId); return new GenericBadRequestException("Bad http request", badHttpRequestException.Message); diff --git a/docs/development.md b/docs/development.md index 457f177b7..a090f243b 100644 --- a/docs/development.md +++ b/docs/development.md @@ -3,7 +3,7 @@ ## Pre-requisites The following are pre-requisites: -* We use [dotnet 7](https://dotnet.microsoft.com/download/dotnet/7.0) - ensure `dotnet --version` returns at least 7.x +* We use [dotnet 8](https://dotnet.microsoft.com/en-us/download/dotnet/8.0) - ensure `dotnet --version` returns at least `8.x` * Install docker Whilst any IDE supporting dotnet core can be used for development, we would recommend Jetbrains Rider. @@ -14,7 +14,7 @@ In development, configuration comes from a few places, with items lower down the * `apps/[X]/appsettings.json` * `apps/[X]/appsettings.Development.json` -* `apps/[X]/appsettings.PersonalOverrides.json` (under .gitignore) +* `apps/[X]/appsettings.overrides.json` (under .gitignore) * Environment variables By default, the configuration is set up to point to a full node's Core API running locally at http://localhost:3333, but you may wish to use non-local Core API, to have a synced-up system to read from, and to avoid hammering your computer too much! (see sections below). @@ -23,7 +23,7 @@ If you wish to easily spin up a local Core API, follow the instructions in [the ### Custom development configuration -As referenced above, the `appsettings.PersonalOverrides.json` files can be used to (eg) override configuration locally without risking updating source control. The schema for this file is the same as the main `appsettings.json` and `appsettings.Development.json`. Some example use cases include: +As referenced above, the `appsettings.overrides.json` files can be used to (eg) override configuration locally without risking updating source control. The schema for this file is the same as the main `appsettings.json` and `appsettings.Development.json`. Some example use cases include: * Changing the `NetworkName` so it matches the core nodes you're connected to * Connecting to a non-local Core Node (typically by adjusting `DisableCoreApiHttpsCertificateChecks`, and the `CoreApiAddress`, `CoreApiAuthorizationHeader` fields under the first configured node in `CoreApiNodes`) @@ -48,15 +48,27 @@ You'll need to run a version 1.1.0 or higher in order for the node to have the C Run following tasks: -* `Postgres` (this runs `docker-compose up`) -* `Database Migrations with Wipe Database` (this runs database migrations) +* `./deployment/run-only-network-gateway-resources.sh` from the command line to start the PostgreSQL DB container. +* `Migrations (Wipe)` (this runs database migrations) And then, depending on what you're working on, you can run one or both of these. Note that the `Data Aggregator` needs to have run successfully at least once to start the ledger, for the `Gateway API` to be able to connect. * `Data Aggregator` -* `Gateway API` +* `Gateway Api` -You can use the `Database Migrations with Wipe Database` task if you ever need to clear the database. (Say, because the DB ledger got corrupted; or you wish to change which network you're connected to) +You can use the `Migrations (Wipe)` task if you ever need to clear the database. (Say, because the DB ledger got corrupted; or you wish to change which network you're connected to) + +### Configuring the dev DB as a Data Source + +To get checking and auto-complete on your SQL, you may wish to configure a Data Source in Rider. Note that currently it often doesn't give any auto-complete for [CTEs](https://www.postgresql.org/docs/current/queries-with.html), and some of our queries are dynamically created, but it's still often useful to inspect data. + +To do this, add a PostgreSQL Database connection with parameters: +* Host: `localhost` +* Port: `5432` +* Authentication: `User & Password` +* User: `db_dev_superuser` +* Password: `db_dev_password` +* Database: `radixdlt_ledger` ## Developing using the command line @@ -66,7 +78,7 @@ Run the following in separate terminals: ```bash # Spin up PostgreSQL first -docker-compose up +./deployment/run-only-network-gateway-resources.sh ``` ```bash @@ -108,7 +120,9 @@ For more information, see the [Tests project](../../src/Tests). ## Reformatting -Run `dotnet format` to fix whitespace and other formatting issues across all files. Rider runs this as you save each file, so this likely won't be needed regularly. +Run `./generation/ensure-license-headers.sh` when adding new files to ensure they get license headers. + +You can also run `dotnet format` manually to fix whitespace and other formatting issues across all files. Rider runs this as you save each file, so this likely won't be needed regularly. ## Code Generation - Migrations, Open API specs etc diff --git a/src/RadixDlt.CoreApiSdk/Model/EventTypeIdentifier.cs b/src/RadixDlt.CoreApiSdk/Model/EventTypeIdentifier.cs index 606d21dab..a1b3ef634 100644 --- a/src/RadixDlt.CoreApiSdk/Model/EventTypeIdentifier.cs +++ b/src/RadixDlt.CoreApiSdk/Model/EventTypeIdentifier.cs @@ -72,7 +72,7 @@ public IEnumerable GetEntityAddresses() { yield return TypeReference.FullTypeId.EntityAddress; - foreach (var address in this.Emitter.GetEntityAddresses()) + foreach (var address in Emitter.GetEntityAddresses()) { yield return address; } diff --git a/src/RadixDlt.CoreApiSdk/Model/FunctionEventEmitterIdentifier.cs b/src/RadixDlt.CoreApiSdk/Model/FunctionEventEmitterIdentifier.cs index 91f37e106..2dbba5b13 100644 --- a/src/RadixDlt.CoreApiSdk/Model/FunctionEventEmitterIdentifier.cs +++ b/src/RadixDlt.CoreApiSdk/Model/FunctionEventEmitterIdentifier.cs @@ -70,6 +70,6 @@ public partial class FunctionEventEmitterIdentifier { public override IEnumerable GetEntityAddresses() { - yield return this.PackageAddress; + yield return PackageAddress; } } diff --git a/src/RadixDlt.CoreApiSdk/Model/SchemaDetails.cs b/src/RadixDlt.CoreApiSdk/Model/SchemaDetails.cs index 9a4612d28..514176d2d 100644 --- a/src/RadixDlt.CoreApiSdk/Model/SchemaDetails.cs +++ b/src/RadixDlt.CoreApiSdk/Model/SchemaDetails.cs @@ -1,4 +1,4 @@ -/* Copyright 2021 Radix Publishing Ltd incorporated in Jersey (Channel Islands). +/* Copyright 2021 Radix Publishing Ltd incorporated in Jersey (Channel Islands). * * Licensed under the Radix License, Version 1.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at: diff --git a/src/RadixDlt.CoreApiSdk/Model/TypeInfoModuleFieldTypeInfoSubstate.cs b/src/RadixDlt.CoreApiSdk/Model/TypeInfoModuleFieldTypeInfoSubstate.cs index 82c9a8518..35e1690af 100644 --- a/src/RadixDlt.CoreApiSdk/Model/TypeInfoModuleFieldTypeInfoSubstate.cs +++ b/src/RadixDlt.CoreApiSdk/Model/TypeInfoModuleFieldTypeInfoSubstate.cs @@ -151,7 +151,7 @@ private SchemaDetails ExtractSchemaDetailsFromGenericSubstitution(GenericSubstit remoteGenericSubstitution.ResolvedFullTypeId.EntityAddress, remoteGenericSubstitution.ResolvedFullTypeId.LocalTypeId.Id, remoteGenericSubstitution.ResolvedFullTypeId.LocalTypeId.Kind), - _ => throw new UnreachableException($"Unexpected type of generic substitution {genericSubstitution.GetType()}") + _ => throw new UnreachableException($"Unexpected type of generic substitution {genericSubstitution.GetType()}"), }; } } diff --git a/src/RadixDlt.NetworkGateway.Abstractions/EntityAddress.cs b/src/RadixDlt.NetworkGateway.Abstractions/EntityAddress.cs index e23015f11..8e87f8414 100644 --- a/src/RadixDlt.NetworkGateway.Abstractions/EntityAddress.cs +++ b/src/RadixDlt.NetworkGateway.Abstractions/EntityAddress.cs @@ -1,4 +1,4 @@ -/* Copyright 2021 Radix Publishing Ltd incorporated in Jersey (Channel Islands). +/* Copyright 2021 Radix Publishing Ltd incorporated in Jersey (Channel Islands). * * Licensed under the Radix License, Version 1.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at: diff --git a/src/RadixDlt.NetworkGateway.DataAggregator/Services/IPendingTransactionResubmissionServiceObserver.cs b/src/RadixDlt.NetworkGateway.DataAggregator/Services/IPendingTransactionResubmissionServiceObserver.cs index 5f2df0af5..cfe25b8b3 100644 --- a/src/RadixDlt.NetworkGateway.DataAggregator/Services/IPendingTransactionResubmissionServiceObserver.cs +++ b/src/RadixDlt.NetworkGateway.DataAggregator/Services/IPendingTransactionResubmissionServiceObserver.cs @@ -67,7 +67,7 @@ namespace RadixDlt.NetworkGateway.DataAggregator.Services; -public interface IPendingTransactionResubmissionServiceObserver: ITransactionSubmitterObserver +public interface IPendingTransactionResubmissionServiceObserver : ITransactionSubmitterObserver { ValueTask ObserveResubmissionQueueSize(int totalTransactionsNeedingResubmission); diff --git a/src/RadixDlt.NetworkGateway.GatewayApi/Exceptions/ClientConnectionClosedException.cs b/src/RadixDlt.NetworkGateway.GatewayApi/Exceptions/ClientConnectionClosedException.cs index c9516bfd5..19d09dd6a 100644 --- a/src/RadixDlt.NetworkGateway.GatewayApi/Exceptions/ClientConnectionClosedException.cs +++ b/src/RadixDlt.NetworkGateway.GatewayApi/Exceptions/ClientConnectionClosedException.cs @@ -1,4 +1,4 @@ -/* Copyright 2021 Radix Publishing Ltd incorporated in Jersey (Channel Islands). +/* Copyright 2021 Radix Publishing Ltd incorporated in Jersey (Channel Islands). * * Licensed under the Radix License, Version 1.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at: diff --git a/src/RadixDlt.NetworkGateway.GatewayApi/Handlers/DefaultTransactionHandler.cs b/src/RadixDlt.NetworkGateway.GatewayApi/Handlers/DefaultTransactionHandler.cs index dfb9ec3c1..d736c2696 100644 --- a/src/RadixDlt.NetworkGateway.GatewayApi/Handlers/DefaultTransactionHandler.cs +++ b/src/RadixDlt.NetworkGateway.GatewayApi/Handlers/DefaultTransactionHandler.cs @@ -250,43 +250,43 @@ public DefaultTransactionHandler( switch (decidingFactorItem.ResourcePreferenceRule) { case GatewayModel.AccountResourcePreferenceRule.Allowed: - { - var resourceSpecificResponseItem = new GatewayModel.AccountDepositPreValidationResourceSpecificBehaviourItem(decidingFactorItem.ResourceAddress, true); - resourceSpecificResponseCollection.Add(resourceSpecificResponseItem); - break; - } + { + var resourceSpecificResponseItem = new GatewayModel.AccountDepositPreValidationResourceSpecificBehaviourItem(decidingFactorItem.ResourceAddress, true); + resourceSpecificResponseCollection.Add(resourceSpecificResponseItem); + break; + } case GatewayModel.AccountResourcePreferenceRule.Disallowed: - { - var resourceSpecificResponseItem = new GatewayModel.AccountDepositPreValidationResourceSpecificBehaviourItem(decidingFactorItem.ResourceAddress, false); - resourceSpecificResponseCollection.Add(resourceSpecificResponseItem); - break; - } + { + var resourceSpecificResponseItem = new GatewayModel.AccountDepositPreValidationResourceSpecificBehaviourItem(decidingFactorItem.ResourceAddress, false); + resourceSpecificResponseCollection.Add(resourceSpecificResponseItem); + break; + } case null: switch (decidingFactors.DefaultDepositRule) { case GatewayModel.AccountDefaultDepositRule.Reject: - { - var resourceSpecificResponseItem = new GatewayModel.AccountDepositPreValidationResourceSpecificBehaviourItem(decidingFactorItem.ResourceAddress, false); - resourceSpecificResponseCollection.Add(resourceSpecificResponseItem); - break; - } + { + var resourceSpecificResponseItem = new GatewayModel.AccountDepositPreValidationResourceSpecificBehaviourItem(decidingFactorItem.ResourceAddress, false); + resourceSpecificResponseCollection.Add(resourceSpecificResponseItem); + break; + } case GatewayModel.AccountDefaultDepositRule.Accept: - { - var resourceSpecificResponseItem = new GatewayModel.AccountDepositPreValidationResourceSpecificBehaviourItem(decidingFactorItem.ResourceAddress, true); - resourceSpecificResponseCollection.Add(resourceSpecificResponseItem); - break; - } + { + var resourceSpecificResponseItem = new GatewayModel.AccountDepositPreValidationResourceSpecificBehaviourItem(decidingFactorItem.ResourceAddress, true); + resourceSpecificResponseCollection.Add(resourceSpecificResponseItem); + break; + } case GatewayModel.AccountDefaultDepositRule.AllowExisting: - { - var allowsTryDeposit = decidingFactorItem.IsXrd || decidingFactorItem.VaultExists; - var resourceSpecificResponseItem = new GatewayModel.AccountDepositPreValidationResourceSpecificBehaviourItem(decidingFactorItem.ResourceAddress, allowsTryDeposit); - resourceSpecificResponseCollection.Add(resourceSpecificResponseItem); - break; - } + { + var allowsTryDeposit = decidingFactorItem.IsXrd || decidingFactorItem.VaultExists; + var resourceSpecificResponseItem = new GatewayModel.AccountDepositPreValidationResourceSpecificBehaviourItem(decidingFactorItem.ResourceAddress, allowsTryDeposit); + resourceSpecificResponseCollection.Add(resourceSpecificResponseItem); + break; + } default: throw new ArgumentOutOfRangeException($"Unexpected value of {decidingFactors.DefaultDepositRule}"); diff --git a/src/RadixDlt.NetworkGateway.GatewayApi/Handlers/DefaultValidatorHandler.cs b/src/RadixDlt.NetworkGateway.GatewayApi/Handlers/DefaultValidatorHandler.cs index baade7ca6..e850994f4 100644 --- a/src/RadixDlt.NetworkGateway.GatewayApi/Handlers/DefaultValidatorHandler.cs +++ b/src/RadixDlt.NetworkGateway.GatewayApi/Handlers/DefaultValidatorHandler.cs @@ -1,4 +1,4 @@ -/* Copyright 2021 Radix Publishing Ltd incorporated in Jersey (Channel Islands). +/* Copyright 2021 Radix Publishing Ltd incorporated in Jersey (Channel Islands). * * Licensed under the Radix License, Version 1.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at: diff --git a/src/RadixDlt.NetworkGateway.GatewayApi/Handlers/IValidatorHandler.cs b/src/RadixDlt.NetworkGateway.GatewayApi/Handlers/IValidatorHandler.cs index 2e8cad308..f5d3246d7 100644 --- a/src/RadixDlt.NetworkGateway.GatewayApi/Handlers/IValidatorHandler.cs +++ b/src/RadixDlt.NetworkGateway.GatewayApi/Handlers/IValidatorHandler.cs @@ -1,4 +1,4 @@ -/* Copyright 2021 Radix Publishing Ltd incorporated in Jersey (Channel Islands). +/* Copyright 2021 Radix Publishing Ltd incorporated in Jersey (Channel Islands). * * Licensed under the Radix License, Version 1.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at: diff --git a/src/RadixDlt.NetworkGateway.GatewayApi/Services/ISubmissionTrackingServiceObserver.cs b/src/RadixDlt.NetworkGateway.GatewayApi/Services/ISubmissionTrackingServiceObserver.cs index 91d766a95..3f60af6e9 100644 --- a/src/RadixDlt.NetworkGateway.GatewayApi/Services/ISubmissionTrackingServiceObserver.cs +++ b/src/RadixDlt.NetworkGateway.GatewayApi/Services/ISubmissionTrackingServiceObserver.cs @@ -67,7 +67,7 @@ namespace RadixDlt.NetworkGateway.GatewayApi.Services; -public interface ISubmissionTrackingServiceObserver: ITransactionSubmitterObserver +public interface ISubmissionTrackingServiceObserver : ITransactionSubmitterObserver { ValueTask OnSubmissionTrackedInDatabase(bool isDuplicate); } diff --git a/src/RadixDlt.NetworkGateway.GatewayApi/Services/IValidatorQuerier.cs b/src/RadixDlt.NetworkGateway.GatewayApi/Services/IValidatorQuerier.cs index 69e4e51d1..20214f210 100644 --- a/src/RadixDlt.NetworkGateway.GatewayApi/Services/IValidatorQuerier.cs +++ b/src/RadixDlt.NetworkGateway.GatewayApi/Services/IValidatorQuerier.cs @@ -1,4 +1,4 @@ -/* Copyright 2021 Radix Publishing Ltd incorporated in Jersey (Channel Islands). +/* Copyright 2021 Radix Publishing Ltd incorporated in Jersey (Channel Islands). * * Licensed under the Radix License, Version 1.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at: diff --git a/src/RadixDlt.NetworkGateway.GatewayApi/Validators/ValidatorsUptimeRequestValidator.cs b/src/RadixDlt.NetworkGateway.GatewayApi/Validators/ValidatorsUptimeRequestValidator.cs index ab87a608f..1d485ec1a 100644 --- a/src/RadixDlt.NetworkGateway.GatewayApi/Validators/ValidatorsUptimeRequestValidator.cs +++ b/src/RadixDlt.NetworkGateway.GatewayApi/Validators/ValidatorsUptimeRequestValidator.cs @@ -1,4 +1,4 @@ -/* Copyright 2021 Radix Publishing Ltd incorporated in Jersey (Channel Islands). +/* Copyright 2021 Radix Publishing Ltd incorporated in Jersey (Channel Islands). * * Licensed under the Radix License, Version 1.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at: diff --git a/src/RadixDlt.NetworkGateway.GatewayApiSdk/Model/StateAccountLockerPageVaultsRequest.cs b/src/RadixDlt.NetworkGateway.GatewayApiSdk/Model/StateAccountLockerPageVaultsRequest.cs index 6d3e426a3..e82a9cb27 100644 --- a/src/RadixDlt.NetworkGateway.GatewayApiSdk/Model/StateAccountLockerPageVaultsRequest.cs +++ b/src/RadixDlt.NetworkGateway.GatewayApiSdk/Model/StateAccountLockerPageVaultsRequest.cs @@ -66,5 +66,4 @@ namespace RadixDlt.NetworkGateway.GatewayApiSdk.Model; public partial class StateAccountLockerPageVaultsRequest : IPaginableRequest { - } diff --git a/src/RadixDlt.NetworkGateway.GatewayApiSdk/Model/StateEntitySchemaPageRequest.cs b/src/RadixDlt.NetworkGateway.GatewayApiSdk/Model/StateEntitySchemaPageRequest.cs index 2aa5b534e..8a06c08bb 100644 --- a/src/RadixDlt.NetworkGateway.GatewayApiSdk/Model/StateEntitySchemaPageRequest.cs +++ b/src/RadixDlt.NetworkGateway.GatewayApiSdk/Model/StateEntitySchemaPageRequest.cs @@ -66,5 +66,4 @@ namespace RadixDlt.NetworkGateway.GatewayApiSdk.Model; public partial class StateEntitySchemaPageRequest : IPaginableRequest { - } diff --git a/src/RadixDlt.NetworkGateway.PostgresIntegration/LedgerExtension/AccountAuthorizedDepositorsProcessor.cs b/src/RadixDlt.NetworkGateway.PostgresIntegration/LedgerExtension/AccountAuthorizedDepositorsProcessor.cs index 80f75f795..f517aaefb 100644 --- a/src/RadixDlt.NetworkGateway.PostgresIntegration/LedgerExtension/AccountAuthorizedDepositorsProcessor.cs +++ b/src/RadixDlt.NetworkGateway.PostgresIntegration/LedgerExtension/AccountAuthorizedDepositorsProcessor.cs @@ -233,28 +233,28 @@ AccountAuthorizedDepositorsChangePointerLookup lookup switch (accountAuthorizedDepositorEntrySubstate.Key.Badge) { case CoreModel.ResourceAuthorizedDepositorBadge resourceBadge: - { - var resourceEntityId = _referencedEntityDictionary.Get((EntityAddress)resourceBadge.ResourceAddress).DatabaseId; - - entryLookup = new AccountAuthorizedDepositorsDbLookup( - AccountEntityId: lookup.AccountEntityId, - ResourceEntityId: resourceEntityId, - NonFungibleId: null - ); - break; - } + { + var resourceEntityId = _referencedEntityDictionary.Get((EntityAddress)resourceBadge.ResourceAddress).DatabaseId; + + entryLookup = new AccountAuthorizedDepositorsDbLookup( + AccountEntityId: lookup.AccountEntityId, + ResourceEntityId: resourceEntityId, + NonFungibleId: null + ); + break; + } case CoreModel.NonFungibleAuthorizedDepositorBadge nonFungibleBadge: - { - var resourceEntityId = _referencedEntityDictionary.Get((EntityAddress)nonFungibleBadge.NonFungibleGlobalId.ResourceAddress).DatabaseId; - - entryLookup = new AccountAuthorizedDepositorsDbLookup( - AccountEntityId: lookup.AccountEntityId, - ResourceEntityId: resourceEntityId, - NonFungibleId: nonFungibleBadge.NonFungibleGlobalId.LocalId.SimpleRep - ); - break; - } + { + var resourceEntityId = _referencedEntityDictionary.Get((EntityAddress)nonFungibleBadge.NonFungibleGlobalId.ResourceAddress).DatabaseId; + + entryLookup = new AccountAuthorizedDepositorsDbLookup( + AccountEntityId: lookup.AccountEntityId, + ResourceEntityId: resourceEntityId, + NonFungibleId: nonFungibleBadge.NonFungibleGlobalId.LocalId.SimpleRep + ); + break; + } default: throw new UnreachableException( diff --git a/src/RadixDlt.NetworkGateway.PostgresIntegration/LedgerExtension/KeyValueStoreProcessor.cs b/src/RadixDlt.NetworkGateway.PostgresIntegration/LedgerExtension/KeyValueStoreProcessor.cs index 122584962..ddcf4f1eb 100644 --- a/src/RadixDlt.NetworkGateway.PostgresIntegration/LedgerExtension/KeyValueStoreProcessor.cs +++ b/src/RadixDlt.NetworkGateway.PostgresIntegration/LedgerExtension/KeyValueStoreProcessor.cs @@ -1,4 +1,4 @@ -/* Copyright 2021 Radix Publishing Ltd incorporated in Jersey (Channel Islands). +/* Copyright 2021 Radix Publishing Ltd incorporated in Jersey (Channel Islands). * * Licensed under the Radix License, Version 1.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at: diff --git a/src/RadixDlt.NetworkGateway.PostgresIntegration/LedgerExtension/ManifestAddressesExtractor.cs b/src/RadixDlt.NetworkGateway.PostgresIntegration/LedgerExtension/ManifestAddressesExtractor.cs index 14e15f703..be2414ad4 100644 --- a/src/RadixDlt.NetworkGateway.PostgresIntegration/LedgerExtension/ManifestAddressesExtractor.cs +++ b/src/RadixDlt.NetworkGateway.PostgresIntegration/LedgerExtension/ManifestAddressesExtractor.cs @@ -1,4 +1,4 @@ -/* Copyright 2021 Radix Publishing Ltd incorporated in Jersey (Channel Islands). +/* Copyright 2021 Radix Publishing Ltd incorporated in Jersey (Channel Islands). * * Licensed under the Radix License, Version 1.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at: @@ -159,18 +159,18 @@ private static List ExtractProofs(Dictionary UpdatePendingTransactions(ReadWriteDbContext dbContext, .Where(pt => pt.LedgerDetails.PayloadLedgerStatus == PendingTransactionPayloadLedgerStatus.PermanentlyRejected) .Select( pt => new - { - pt.PayloadHash, - pt.LedgerDetails.PayloadLedgerStatus, - pt.GatewayHandling.FirstSubmittedToGatewayTimestamp, - pt.LedgerDetails.LatestRejectionTimestamp, - pt.LedgerDetails.LatestRejectionReason, - }) + { + pt.PayloadHash, + pt.LedgerDetails.PayloadLedgerStatus, + pt.GatewayHandling.FirstSubmittedToGatewayTimestamp, + pt.LedgerDetails.LatestRejectionTimestamp, + pt.LedgerDetails.LatestRejectionReason, + }) .AnnotateMetricName() .ToListAsync(token); @@ -286,11 +286,11 @@ private async Task ProcessTransactions(ReadWriteDbContext db { ledgerTransactionMarkersToAdd.Add( new OriginLedgerTransactionMarker - { - Id = sequences.LedgerTransactionMarkerSequence++, - StateVersion = stateVersion, - OriginType = LedgerTransactionMarkerOriginType.User, - }); + { + Id = sequences.LedgerTransactionMarkerSequence++, + StateVersion = stateVersion, + OriginType = LedgerTransactionMarkerOriginType.User, + }); var coreInstructions = userLedgerTransaction.NotarizedTransaction.SignedIntent.Intent.Instructions; var coreBlobs = userLedgerTransaction.NotarizedTransaction.SignedIntent.Intent.BlobsHex; @@ -318,12 +318,12 @@ private async Task ProcessTransactions(ReadWriteDbContext db ledgerTransactionMarkersToAdd.Add( new ManifestClassMarker - { - Id = sequences.LedgerTransactionMarkerSequence++, - StateVersion = stateVersion, - ManifestClass = manifestClass, - IsMostSpecific = i == 0, - }); + { + Id = sequences.LedgerTransactionMarkerSequence++, + StateVersion = stateVersion, + ManifestClass = manifestClass, + IsMostSpecific = i == 0, + }); } } @@ -340,31 +340,31 @@ private async Task ProcessTransactions(ReadWriteDbContext db referencedEntity.WithTypeHint( newGlobalEntity.EntityType switch - { - CoreModel.EntityType.GlobalPackage => typeof(GlobalPackageEntity), - CoreModel.EntityType.GlobalConsensusManager => typeof(GlobalConsensusManager), - CoreModel.EntityType.GlobalValidator => typeof(GlobalValidatorEntity), - CoreModel.EntityType.GlobalGenericComponent => typeof(GlobalGenericComponentEntity), - CoreModel.EntityType.GlobalAccount => typeof(GlobalAccountEntity), - CoreModel.EntityType.GlobalAccountLocker => typeof(GlobalAccountLockerEntity), - CoreModel.EntityType.GlobalIdentity => typeof(GlobalIdentityEntity), - CoreModel.EntityType.GlobalAccessController => typeof(GlobalAccessControllerEntity), - CoreModel.EntityType.GlobalVirtualSecp256k1Account => typeof(GlobalAccountEntity), - CoreModel.EntityType.GlobalVirtualSecp256k1Identity => typeof(GlobalIdentityEntity), - CoreModel.EntityType.GlobalVirtualEd25519Account => typeof(GlobalAccountEntity), - CoreModel.EntityType.GlobalVirtualEd25519Identity => typeof(GlobalIdentityEntity), - CoreModel.EntityType.GlobalFungibleResource => typeof(GlobalFungibleResourceEntity), - CoreModel.EntityType.InternalFungibleVault => typeof(InternalFungibleVaultEntity), - CoreModel.EntityType.GlobalNonFungibleResource => typeof(GlobalNonFungibleResourceEntity), - CoreModel.EntityType.InternalNonFungibleVault => typeof(InternalNonFungibleVaultEntity), - CoreModel.EntityType.InternalGenericComponent => typeof(InternalGenericComponentEntity), - CoreModel.EntityType.InternalKeyValueStore => typeof(InternalKeyValueStoreEntity), - CoreModel.EntityType.GlobalOneResourcePool => typeof(GlobalOneResourcePoolEntity), - CoreModel.EntityType.GlobalTwoResourcePool => typeof(GlobalTwoResourcePoolEntity), - CoreModel.EntityType.GlobalMultiResourcePool => typeof(GlobalMultiResourcePoolEntity), - CoreModel.EntityType.GlobalTransactionTracker => typeof(GlobalTransactionTrackerEntity), - _ => throw new ArgumentOutOfRangeException(nameof(newGlobalEntity.EntityType), newGlobalEntity.EntityType.ToString()), - }); + { + CoreModel.EntityType.GlobalPackage => typeof(GlobalPackageEntity), + CoreModel.EntityType.GlobalConsensusManager => typeof(GlobalConsensusManager), + CoreModel.EntityType.GlobalValidator => typeof(GlobalValidatorEntity), + CoreModel.EntityType.GlobalGenericComponent => typeof(GlobalGenericComponentEntity), + CoreModel.EntityType.GlobalAccount => typeof(GlobalAccountEntity), + CoreModel.EntityType.GlobalAccountLocker => typeof(GlobalAccountLockerEntity), + CoreModel.EntityType.GlobalIdentity => typeof(GlobalIdentityEntity), + CoreModel.EntityType.GlobalAccessController => typeof(GlobalAccessControllerEntity), + CoreModel.EntityType.GlobalVirtualSecp256k1Account => typeof(GlobalAccountEntity), + CoreModel.EntityType.GlobalVirtualSecp256k1Identity => typeof(GlobalIdentityEntity), + CoreModel.EntityType.GlobalVirtualEd25519Account => typeof(GlobalAccountEntity), + CoreModel.EntityType.GlobalVirtualEd25519Identity => typeof(GlobalIdentityEntity), + CoreModel.EntityType.GlobalFungibleResource => typeof(GlobalFungibleResourceEntity), + CoreModel.EntityType.InternalFungibleVault => typeof(InternalFungibleVaultEntity), + CoreModel.EntityType.GlobalNonFungibleResource => typeof(GlobalNonFungibleResourceEntity), + CoreModel.EntityType.InternalNonFungibleVault => typeof(InternalNonFungibleVaultEntity), + CoreModel.EntityType.InternalGenericComponent => typeof(InternalGenericComponentEntity), + CoreModel.EntityType.InternalKeyValueStore => typeof(InternalKeyValueStoreEntity), + CoreModel.EntityType.GlobalOneResourcePool => typeof(GlobalOneResourcePoolEntity), + CoreModel.EntityType.GlobalTwoResourcePool => typeof(GlobalTwoResourcePoolEntity), + CoreModel.EntityType.GlobalMultiResourcePool => typeof(GlobalMultiResourcePoolEntity), + CoreModel.EntityType.GlobalTransactionTracker => typeof(GlobalTransactionTrackerEntity), + _ => throw new ArgumentOutOfRangeException(nameof(newGlobalEntity.EntityType), newGlobalEntity.EntityType.ToString()), + }); } foreach (var substate in stateUpdates.UpsertedSubstates) @@ -571,11 +571,11 @@ private async Task ProcessTransactions(ReadWriteDbContext db { ledgerTransactionMarkersToAdd.Add( new OriginLedgerTransactionMarker - { - Id = sequences.LedgerTransactionMarkerSequence++, - StateVersion = stateVersion, - OriginType = LedgerTransactionMarkerOriginType.EpochChange, - }); + { + Id = sequences.LedgerTransactionMarkerSequence++, + StateVersion = stateVersion, + OriginType = LedgerTransactionMarkerOriginType.EpochChange, + }); } lastTransactionSummary = summary; @@ -864,15 +864,15 @@ private async Task ProcessTransactions(ReadWriteDbContext db nonFungibleSchemaHistoryToAdd.Add( new NonFungibleSchemaHistory - { - Id = sequences.NonFungibleSchemaHistorySequence++, - ResourceEntityId = referencedEntity.DatabaseId, - SchemaHash = nonFungibleDataSchemaDetails.Value.SchemaHash.ConvertFromHex(), - SborTypeKind = nonFungibleDataSchemaDetails.Value.SborTypeKind.ToModel(), - TypeIndex = nonFungibleDataSchemaDetails.Value.TypeIndex, - SchemaDefiningEntityId = schemaDefiningEntityId, - FromStateVersion = stateVersion, - }); + { + Id = sequences.NonFungibleSchemaHistorySequence++, + ResourceEntityId = referencedEntity.DatabaseId, + SchemaHash = nonFungibleDataSchemaDetails.Value.SchemaHash.ConvertFromHex(), + SborTypeKind = nonFungibleDataSchemaDetails.Value.SborTypeKind.ToModel(), + TypeIndex = nonFungibleDataSchemaDetails.Value.TypeIndex, + SchemaDefiningEntityId = schemaDefiningEntityId, + FromStateVersion = stateVersion, + }); } if (typeInfoSubstate.Value.Details is CoreModel.KeyValueStoreTypeInfoDetails @@ -889,19 +889,19 @@ private async Task ProcessTransactions(ReadWriteDbContext db keyValueStoreSchemaHistoryToAdd.Add( new KeyValueStoreSchemaHistory - { - Id = sequences.KeyValueSchemaHistorySequence++, - KeyValueStoreEntityId = referencedEntity.DatabaseId, - KeySchemaDefiningEntityId = keySchemaDefiningEntityId, - KeySchemaHash = keySchemaDetails.Value.SchemaHash.ConvertFromHex(), - KeySborTypeKind = keySchemaDetails.Value.SborTypeKind.ToModel(), - KeyTypeIndex = keySchemaDetails.Value.TypeIndex, - ValueSchemaDefiningEntityId = valueSchemaDefiningEntityId, - ValueSchemaHash = valueSchemaDetails.Value.SchemaHash.ConvertFromHex(), - ValueSborTypeKind = valueSchemaDetails.Value.SborTypeKind.ToModel(), - ValueTypeIndex = valueSchemaDetails.Value.TypeIndex, - FromStateVersion = stateVersion, - }); + { + Id = sequences.KeyValueSchemaHistorySequence++, + KeyValueStoreEntityId = referencedEntity.DatabaseId, + KeySchemaDefiningEntityId = keySchemaDefiningEntityId, + KeySchemaHash = keySchemaDetails.Value.SchemaHash.ConvertFromHex(), + KeySborTypeKind = keySchemaDetails.Value.SborTypeKind.ToModel(), + KeyTypeIndex = keySchemaDetails.Value.TypeIndex, + ValueSchemaDefiningEntityId = valueSchemaDefiningEntityId, + ValueSchemaHash = valueSchemaDetails.Value.SchemaHash.ConvertFromHex(), + ValueSborTypeKind = valueSchemaDetails.Value.SborTypeKind.ToModel(), + ValueTypeIndex = valueSchemaDetails.Value.TypeIndex, + FromStateVersion = stateVersion, + }); } } @@ -973,53 +973,53 @@ private async Task ProcessTransactions(ReadWriteDbContext db { ledgerTransactionMarkersToAdd.Add( new EventLedgerTransactionMarker - { - Id = sequences.LedgerTransactionMarkerSequence++, - StateVersion = stateVersion, - EventType = LedgerTransactionMarkerEventType.Withdrawal, - EntityId = eventEmitterEntity.DatabaseGlobalAncestorId, - ResourceEntityId = eventEmitterEntity.GetDatabaseEntity().GetResourceEntityId(), - Quantity = TokenAmount.FromDecimalString(fungibleVaultWithdrawalEvent.AsStr()), - }); + { + Id = sequences.LedgerTransactionMarkerSequence++, + StateVersion = stateVersion, + EventType = LedgerTransactionMarkerEventType.Withdrawal, + EntityId = eventEmitterEntity.DatabaseGlobalAncestorId, + ResourceEntityId = eventEmitterEntity.GetDatabaseEntity().GetResourceEntityId(), + Quantity = TokenAmount.FromDecimalString(fungibleVaultWithdrawalEvent.AsStr()), + }); } else if (EventDecoder.TryGetFungibleVaultDepositEvent(decodedEvent, out var fungibleVaultDepositEvent)) { ledgerTransactionMarkersToAdd.Add( new EventLedgerTransactionMarker - { - Id = sequences.LedgerTransactionMarkerSequence++, - StateVersion = stateVersion, - EventType = LedgerTransactionMarkerEventType.Deposit, - EntityId = eventEmitterEntity.DatabaseGlobalAncestorId, - ResourceEntityId = eventEmitterEntity.GetDatabaseEntity().GetResourceEntityId(), - Quantity = TokenAmount.FromDecimalString(fungibleVaultDepositEvent.AsStr()), - }); + { + Id = sequences.LedgerTransactionMarkerSequence++, + StateVersion = stateVersion, + EventType = LedgerTransactionMarkerEventType.Deposit, + EntityId = eventEmitterEntity.DatabaseGlobalAncestorId, + ResourceEntityId = eventEmitterEntity.GetDatabaseEntity().GetResourceEntityId(), + Quantity = TokenAmount.FromDecimalString(fungibleVaultDepositEvent.AsStr()), + }); } else if (EventDecoder.TryGetNonFungibleVaultWithdrawalEvent(decodedEvent, out var nonFungibleVaultWithdrawalEvent)) { ledgerTransactionMarkersToAdd.Add( new EventLedgerTransactionMarker - { - Id = sequences.LedgerTransactionMarkerSequence++, - StateVersion = stateVersion, - EventType = LedgerTransactionMarkerEventType.Withdrawal, - EntityId = eventEmitterEntity.DatabaseGlobalAncestorId, - ResourceEntityId = eventEmitterEntity.GetDatabaseEntity().GetResourceEntityId(), - Quantity = TokenAmount.FromDecimalString(nonFungibleVaultWithdrawalEvent.Length.ToString()), - }); + { + Id = sequences.LedgerTransactionMarkerSequence++, + StateVersion = stateVersion, + EventType = LedgerTransactionMarkerEventType.Withdrawal, + EntityId = eventEmitterEntity.DatabaseGlobalAncestorId, + ResourceEntityId = eventEmitterEntity.GetDatabaseEntity().GetResourceEntityId(), + Quantity = TokenAmount.FromDecimalString(nonFungibleVaultWithdrawalEvent.Length.ToString()), + }); } else if (EventDecoder.TryGetNonFungibleVaultDepositEvent(decodedEvent, out var nonFungibleVaultDepositEvent)) { ledgerTransactionMarkersToAdd.Add( new EventLedgerTransactionMarker - { - Id = sequences.LedgerTransactionMarkerSequence++, - StateVersion = stateVersion, - EventType = LedgerTransactionMarkerEventType.Deposit, - EntityId = eventEmitterEntity.DatabaseGlobalAncestorId, - ResourceEntityId = eventEmitterEntity.GetDatabaseEntity().GetResourceEntityId(), - Quantity = TokenAmount.FromDecimalString(nonFungibleVaultDepositEvent.Length.ToString()), - }); + { + Id = sequences.LedgerTransactionMarkerSequence++, + StateVersion = stateVersion, + EventType = LedgerTransactionMarkerEventType.Deposit, + EntityId = eventEmitterEntity.DatabaseGlobalAncestorId, + ResourceEntityId = eventEmitterEntity.GetDatabaseEntity().GetResourceEntityId(), + Quantity = TokenAmount.FromDecimalString(nonFungibleVaultDepositEvent.Length.ToString()), + }); } else if (EventDecoder.TryGetFungibleResourceMintedEvent(decodedEvent, out var fungibleResourceMintedEvent)) { @@ -1066,12 +1066,12 @@ private async Task ProcessTransactions(ReadWriteDbContext db { ledgerTransactionMarkersToAdd.Add( new ManifestAddressLedgerTransactionMarker - { - Id = sequences.LedgerTransactionMarkerSequence++, - StateVersion = stateVersion, - OperationType = LedgerTransactionMarkerOperationType.ResourceInUse, - EntityId = re.DatabaseId, - }); + { + Id = sequences.LedgerTransactionMarkerSequence++, + StateVersion = stateVersion, + OperationType = LedgerTransactionMarkerOperationType.ResourceInUse, + EntityId = re.DatabaseId, + }); } } @@ -1081,12 +1081,12 @@ private async Task ProcessTransactions(ReadWriteDbContext db { ledgerTransactionMarkersToAdd.Add( new ManifestAddressLedgerTransactionMarker - { - Id = sequences.LedgerTransactionMarkerSequence++, - StateVersion = stateVersion, - OperationType = LedgerTransactionMarkerOperationType.AccountOwnerMethodCall, - EntityId = re.DatabaseId, - }); + { + Id = sequences.LedgerTransactionMarkerSequence++, + StateVersion = stateVersion, + OperationType = LedgerTransactionMarkerOperationType.AccountOwnerMethodCall, + EntityId = re.DatabaseId, + }); } } @@ -1096,12 +1096,12 @@ private async Task ProcessTransactions(ReadWriteDbContext db { ledgerTransactionMarkersToAdd.Add( new ManifestAddressLedgerTransactionMarker - { - Id = sequences.LedgerTransactionMarkerSequence++, - StateVersion = stateVersion, - OperationType = LedgerTransactionMarkerOperationType.AccountDepositedInto, - EntityId = re.DatabaseId, - }); + { + Id = sequences.LedgerTransactionMarkerSequence++, + StateVersion = stateVersion, + OperationType = LedgerTransactionMarkerOperationType.AccountDepositedInto, + EntityId = re.DatabaseId, + }); } } @@ -1111,12 +1111,12 @@ private async Task ProcessTransactions(ReadWriteDbContext db { ledgerTransactionMarkersToAdd.Add( new ManifestAddressLedgerTransactionMarker - { - Id = sequences.LedgerTransactionMarkerSequence++, - StateVersion = stateVersion, - OperationType = LedgerTransactionMarkerOperationType.AccountWithdrawnFrom, - EntityId = re.DatabaseId, - }); + { + Id = sequences.LedgerTransactionMarkerSequence++, + StateVersion = stateVersion, + OperationType = LedgerTransactionMarkerOperationType.AccountWithdrawnFrom, + EntityId = re.DatabaseId, + }); } } } @@ -1203,14 +1203,14 @@ private async Task ProcessTransactions(ReadWriteDbContext db nonFungibleIdsMutableDataHistoryToAdd.Add( new NonFungibleIdDataHistory - { - Id = sequences.NonFungibleIdDataHistorySequence++, - FromStateVersion = e.StateVersion, - NonFungibleIdDefinitionId = nonFungibleIdData.Id, - Data = e.MutableData, - IsDeleted = e.IsDeleted, - IsLocked = e.IsLocked, - }); + { + Id = sequences.NonFungibleIdDataHistorySequence++, + FromStateVersion = e.StateVersion, + NonFungibleIdDefinitionId = nonFungibleIdData.Id, + Data = e.MutableData, + IsDeleted = e.IsDeleted, + IsLocked = e.IsLocked, + }); } void AggregateEntityResourceUsingSubstates( @@ -1297,72 +1297,72 @@ void AggregateEntityResourceVaultInternal(long entityId, long resourceEntityId, switch (vaultSnapshot) { case FungibleVaultSnapshot fe: - { - AggregateEntityResourceUsingSubstates(fe.ReferencedVault, fe.ReferencedResource, fe.StateVersion, true); - - vaultHistoryToAdd.Add(new EntityFungibleVaultHistory { - Id = sequences.EntityVaultHistorySequence++, - FromStateVersion = fe.StateVersion, - OwnerEntityId = fe.ReferencedVault.DatabaseOwnerAncestorId, - GlobalEntityId = fe.ReferencedVault.DatabaseGlobalAncestorId, - ResourceEntityId = fe.ReferencedResource.DatabaseId, - VaultEntityId = fe.ReferencedVault.DatabaseId, - IsRoyaltyVault = fe.ReferencedVault.GetDatabaseEntity().IsRoyaltyVault, - Balance = fe.Balance, - }); - break; - } - - case NonFungibleVaultSnapshot nfe: - { - AggregateEntityResourceUsingSubstates(nfe.ReferencedVault, nfe.ReferencedResource, nfe.StateVersion, false); + AggregateEntityResourceUsingSubstates(fe.ReferencedVault, fe.ReferencedResource, fe.StateVersion, true); - EntityNonFungibleVaultHistory vaultHistory; - - if (!mostRecentEntityNonFungibleVaultHistory.TryGetValue(nfe.ReferencedVault.DatabaseId, out var previous) || previous.FromStateVersion != nfe.StateVersion) - { - vaultHistory = new EntityNonFungibleVaultHistory + vaultHistoryToAdd.Add(new EntityFungibleVaultHistory { Id = sequences.EntityVaultHistorySequence++, - FromStateVersion = nfe.StateVersion, - OwnerEntityId = nfe.ReferencedVault.DatabaseOwnerAncestorId, - GlobalEntityId = nfe.ReferencedVault.DatabaseGlobalAncestorId, - ResourceEntityId = nfe.ReferencedResource.DatabaseId, - VaultEntityId = nfe.ReferencedVault.DatabaseId, - NonFungibleIds = new List(previous?.NonFungibleIds.ToArray() ?? Array.Empty()), - }; - - vaultHistoryToAdd.Add(vaultHistory); - mostRecentEntityNonFungibleVaultHistory[nfe.ReferencedVault.DatabaseId] = vaultHistory; + FromStateVersion = fe.StateVersion, + OwnerEntityId = fe.ReferencedVault.DatabaseOwnerAncestorId, + GlobalEntityId = fe.ReferencedVault.DatabaseGlobalAncestorId, + ResourceEntityId = fe.ReferencedResource.DatabaseId, + VaultEntityId = fe.ReferencedVault.DatabaseId, + IsRoyaltyVault = fe.ReferencedVault.GetDatabaseEntity().IsRoyaltyVault, + Balance = fe.Balance, + }); + break; } - else + + case NonFungibleVaultSnapshot nfe: { - vaultHistory = previous; - } + AggregateEntityResourceUsingSubstates(nfe.ReferencedVault, nfe.ReferencedResource, nfe.StateVersion, false); - var nonFungibleIdDataId = existingNonFungibleIdData[new NonFungibleIdLookup(nfe.ReferencedResource.DatabaseId, nfe.NonFungibleId)].Id; + EntityNonFungibleVaultHistory vaultHistory; - if (nfe.IsWithdrawal) - { - vaultHistory.NonFungibleIds.Remove(nonFungibleIdDataId); - } - else - { - vaultHistory.NonFungibleIds.Add(nonFungibleIdDataId); + if (!mostRecentEntityNonFungibleVaultHistory.TryGetValue(nfe.ReferencedVault.DatabaseId, out var previous) || previous.FromStateVersion != nfe.StateVersion) + { + vaultHistory = new EntityNonFungibleVaultHistory + { + Id = sequences.EntityVaultHistorySequence++, + FromStateVersion = nfe.StateVersion, + OwnerEntityId = nfe.ReferencedVault.DatabaseOwnerAncestorId, + GlobalEntityId = nfe.ReferencedVault.DatabaseGlobalAncestorId, + ResourceEntityId = nfe.ReferencedResource.DatabaseId, + VaultEntityId = nfe.ReferencedVault.DatabaseId, + NonFungibleIds = new List(previous?.NonFungibleIds.ToArray() ?? Array.Empty()), + }; - nonFungibleIdLocationHistoryToAdd.Add( - new NonFungibleIdLocationHistory + vaultHistoryToAdd.Add(vaultHistory); + mostRecentEntityNonFungibleVaultHistory[nfe.ReferencedVault.DatabaseId] = vaultHistory; + } + else { - Id = sequences.NonFungibleIdLocationHistorySequence++, - FromStateVersion = nfe.StateVersion, - NonFungibleIdDataId = nonFungibleIdDataId, - VaultEntityId = nfe.ReferencedVault.DatabaseId, - }); - } + vaultHistory = previous; + } - break; - } + var nonFungibleIdDataId = existingNonFungibleIdData[new NonFungibleIdLookup(nfe.ReferencedResource.DatabaseId, nfe.NonFungibleId)].Id; + + if (nfe.IsWithdrawal) + { + vaultHistory.NonFungibleIds.Remove(nonFungibleIdDataId); + } + else + { + vaultHistory.NonFungibleIds.Add(nonFungibleIdDataId); + + nonFungibleIdLocationHistoryToAdd.Add( + new NonFungibleIdLocationHistory + { + Id = sequences.NonFungibleIdLocationHistorySequence++, + FromStateVersion = nfe.StateVersion, + NonFungibleIdDataId = nonFungibleIdDataId, + VaultEntityId = nfe.ReferencedVault.DatabaseId, + }); + } + + break; + } default: throw new ArgumentOutOfRangeException(nameof(vaultSnapshot), vaultSnapshot, null); @@ -1376,62 +1376,62 @@ void AggregateEntityResourceVaultInternal(long entityId, long resourceEntityId, switch (vaultChange) { case EntityFungibleResourceBalanceChangeEvent fe: - { - EntityFungibleResourceAggregatedVaultsHistory aggregate; - - if (!mostRecentEntityResourceAggregatedVaultsHistory.TryGetValue(lookup, out var previous) || previous.FromStateVersion != fe.StateVersion) { - var previousBalance = (previous as EntityFungibleResourceAggregatedVaultsHistory)?.Balance ?? TokenAmount.Zero; + EntityFungibleResourceAggregatedVaultsHistory aggregate; - aggregate = new EntityFungibleResourceAggregatedVaultsHistory + if (!mostRecentEntityResourceAggregatedVaultsHistory.TryGetValue(lookup, out var previous) || previous.FromStateVersion != fe.StateVersion) { - Id = sequences.EntityResourceAggregatedVaultsHistorySequence++, - FromStateVersion = fe.StateVersion, - EntityId = fe.EntityId, - ResourceEntityId = fe.ResourceEntityId, - Balance = previousBalance, - }; + var previousBalance = (previous as EntityFungibleResourceAggregatedVaultsHistory)?.Balance ?? TokenAmount.Zero; - entityResourceAggregatedVaultsHistoryToAdd.Add(aggregate); - mostRecentEntityResourceAggregatedVaultsHistory[lookup] = aggregate; - } - else - { - aggregate = (EntityFungibleResourceAggregatedVaultsHistory)previous; - } + aggregate = new EntityFungibleResourceAggregatedVaultsHistory + { + Id = sequences.EntityResourceAggregatedVaultsHistorySequence++, + FromStateVersion = fe.StateVersion, + EntityId = fe.EntityId, + ResourceEntityId = fe.ResourceEntityId, + Balance = previousBalance, + }; - aggregate.Balance += fe.Delta; - break; - } + entityResourceAggregatedVaultsHistoryToAdd.Add(aggregate); + mostRecentEntityResourceAggregatedVaultsHistory[lookup] = aggregate; + } + else + { + aggregate = (EntityFungibleResourceAggregatedVaultsHistory)previous; + } - case EntityNonFungibleResourceBalanceChangeEvent nfe: - { - EntityNonFungibleResourceAggregatedVaultsHistory aggregate; + aggregate.Balance += fe.Delta; + break; + } - if (!mostRecentEntityResourceAggregatedVaultsHistory.TryGetValue(lookup, out var previous) || previous.FromStateVersion != nfe.StateVersion) + case EntityNonFungibleResourceBalanceChangeEvent nfe: { - var previousTotalCount = (previous as EntityNonFungibleResourceAggregatedVaultsHistory)?.TotalCount ?? 0; + EntityNonFungibleResourceAggregatedVaultsHistory aggregate; - aggregate = new EntityNonFungibleResourceAggregatedVaultsHistory + if (!mostRecentEntityResourceAggregatedVaultsHistory.TryGetValue(lookup, out var previous) || previous.FromStateVersion != nfe.StateVersion) { - Id = sequences.EntityResourceAggregatedVaultsHistorySequence++, - FromStateVersion = nfe.StateVersion, - EntityId = nfe.EntityId, - ResourceEntityId = nfe.ResourceEntityId, - TotalCount = previousTotalCount, - }; - - entityResourceAggregatedVaultsHistoryToAdd.Add(aggregate); - mostRecentEntityResourceAggregatedVaultsHistory[lookup] = aggregate; - } - else - { - aggregate = (EntityNonFungibleResourceAggregatedVaultsHistory)previous; - } + var previousTotalCount = (previous as EntityNonFungibleResourceAggregatedVaultsHistory)?.TotalCount ?? 0; - aggregate.TotalCount += nfe.Delta; - break; - } + aggregate = new EntityNonFungibleResourceAggregatedVaultsHistory + { + Id = sequences.EntityResourceAggregatedVaultsHistorySequence++, + FromStateVersion = nfe.StateVersion, + EntityId = nfe.EntityId, + ResourceEntityId = nfe.ResourceEntityId, + TotalCount = previousTotalCount, + }; + + entityResourceAggregatedVaultsHistoryToAdd.Add(aggregate); + mostRecentEntityResourceAggregatedVaultsHistory[lookup] = aggregate; + } + else + { + aggregate = (EntityNonFungibleResourceAggregatedVaultsHistory)previous; + } + + aggregate.TotalCount += nfe.Delta; + break; + } default: throw new ArgumentOutOfRangeException(nameof(vaultChange), vaultChange, null); diff --git a/src/RadixDlt.NetworkGateway.PostgresIntegration/Migrations/20240812074026_InitialCreate.cs b/src/RadixDlt.NetworkGateway.PostgresIntegration/Migrations/20240812074026_InitialCreate.cs index efe0e55ef..ac1de06ab 100644 --- a/src/RadixDlt.NetworkGateway.PostgresIntegration/Migrations/20240812074026_InitialCreate.cs +++ b/src/RadixDlt.NetworkGateway.PostgresIntegration/Migrations/20240812074026_InitialCreate.cs @@ -62,14 +62,14 @@ * permissions under this License. */ -using System; -using System.Collections.Generic; -using System.Numerics; using Microsoft.EntityFrameworkCore.Migrations; using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; using RadixDlt.NetworkGateway.Abstractions.Model; using RadixDlt.NetworkGateway.Abstractions.StandardMetadata; using RadixDlt.NetworkGateway.PostgresIntegration.Models; +using System; +using System.Collections.Generic; +using System.Numerics; #nullable disable diff --git a/src/RadixDlt.NetworkGateway.PostgresIntegration/Services/EntityStateQuerier.cs b/src/RadixDlt.NetworkGateway.PostgresIntegration/Services/EntityStateQuerier.cs index c7127a3be..d409ada7d 100644 --- a/src/RadixDlt.NetworkGateway.PostgresIntegration/Services/EntityStateQuerier.cs +++ b/src/RadixDlt.NetworkGateway.PostgresIntegration/Services/EntityStateQuerier.cs @@ -1430,26 +1430,26 @@ FROM schema_entry_definition result.Add(state.EntityId, jsonStateHistory.JsonState); break; case SborStateHistory sborStateHistory: - { - var schemaIdentifier = new SchemaIdentifier((ValueBytes)sborStateHistory.SchemaHash, sborStateHistory.SchemaDefiningEntityId); - var schemaFound = schemas.TryGetValue(schemaIdentifier, out var schemaBytes); - - if (!schemaFound) { - throw new UnreachableException( - $"schema not found for entity :{sborStateHistory.EntityId} with schema defining entity id: {sborStateHistory.SchemaDefiningEntityId} and schema hash: {sborStateHistory.SchemaHash.ToHex()}"); - } + var schemaIdentifier = new SchemaIdentifier((ValueBytes)sborStateHistory.SchemaHash, sborStateHistory.SchemaDefiningEntityId); + var schemaFound = schemas.TryGetValue(schemaIdentifier, out var schemaBytes); - var jsonState = ScryptoSborUtils.DataToProgrammaticJsonString( - sborStateHistory.SborState, - schemaBytes!, - sborStateHistory.SborTypeKind, - sborStateHistory.TypeIndex, - (await _networkConfigurationProvider.GetNetworkConfiguration(token)).Id); + if (!schemaFound) + { + throw new UnreachableException( + $"schema not found for entity :{sborStateHistory.EntityId} with schema defining entity id: {sborStateHistory.SchemaDefiningEntityId} and schema hash: {sborStateHistory.SchemaHash.ToHex()}"); + } - result.Add(state.EntityId, jsonState); - break; - } + var jsonState = ScryptoSborUtils.DataToProgrammaticJsonString( + sborStateHistory.SborState, + schemaBytes!, + sborStateHistory.SborTypeKind, + sborStateHistory.TypeIndex, + (await _networkConfigurationProvider.GetNetworkConfiguration(token)).Id); + + result.Add(state.EntityId, jsonState); + break; + } } } diff --git a/src/RadixDlt.NetworkGateway.PostgresIntegration/Services/EntityStateQuerier.package.cs b/src/RadixDlt.NetworkGateway.PostgresIntegration/Services/EntityStateQuerier.package.cs index af51c9ad8..d4bc628b7 100644 --- a/src/RadixDlt.NetworkGateway.PostgresIntegration/Services/EntityStateQuerier.package.cs +++ b/src/RadixDlt.NetworkGateway.PostgresIntegration/Services/EntityStateQuerier.package.cs @@ -1,66 +1,66 @@ - /* Copyright 2021 Radix Publishing Ltd incorporated in Jersey (Channel Islands). - * - * Licensed under the Radix License, Version 1.0 (the "License"); you may not use this - * file except in compliance with the License. You may obtain a copy of the License at: - * - * radixfoundation.org/licenses/LICENSE-v1 - * - * The Licensor hereby grants permission for the Canonical version of the Work to be - * published, distributed and used under or by reference to the Licensor’s trademark - * Radix ® and use of any unregistered trade names, logos or get-up. - * - * The Licensor provides the Work (and each Contributor provides its Contributions) on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, - * including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, - * MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. - * - * Whilst the Work is capable of being deployed, used and adopted (instantiated) to create - * a distributed ledger it is your responsibility to test and validate the code, together - * with all logic and performance of that code under all foreseeable scenarios. - * - * The Licensor does not make or purport to make and hereby excludes liability for all - * and any representation, warranty or undertaking in any form whatsoever, whether express - * or implied, to any entity or person, including any representation, warranty or - * undertaking, as to the functionality security use, value or other characteristics of - * any distributed ledger nor in respect the functioning or value of any tokens which may - * be created stored or transferred using the Work. The Licensor does not warrant that the - * Work or any use of the Work complies with any law or regulation in any territory where - * it may be implemented or used or that it will be appropriate for any specific purpose. - * - * Neither the licensor nor any current or former employees, officers, directors, partners, - * trustees, representatives, agents, advisors, contractors, or volunteers of the Licensor - * shall be liable for any direct or indirect, special, incidental, consequential or other - * losses of any kind, in tort, contract or otherwise (including but not limited to loss - * of revenue, income or profits, or loss of use or data, or loss of reputation, or loss - * of any economic or other opportunity of whatsoever nature or howsoever arising), arising - * out of or in connection with (without limitation of any use, misuse, of any ledger system - * or use made or its functionality or any performance or operation of any code or protocol - * caused by bugs or programming or logic errors or otherwise); - * - * A. any offer, purchase, holding, use, sale, exchange or transmission of any - * cryptographic keys, tokens or assets created, exchanged, stored or arising from any - * interaction with the Work; - * - * B. any failure in a transmission or loss of any token or assets keys or other digital - * artefacts due to errors in transmission; - * - * C. bugs, hacks, logic errors or faults in the Work or any communication; - * - * D. system software or apparatus including but not limited to losses caused by errors - * in holding or transmitting tokens by any third-party; - * - * E. breaches or failure of security including hacker attacks, loss or disclosure of - * password, loss of private key, unauthorised use or misuse of such passwords or keys; - * - * F. any losses including loss of anticipated savings or other benefits resulting from - * use of the Work or any changes to the Work (however implemented). - * - * You are solely responsible for; testing, validating and evaluation of all operation - * logic, functionality, security and appropriateness of using the Work for any commercial - * or non-commercial purpose and for any reproduction or redistribution by You of the - * Work. You assume all risks associated with Your use of the Work and the exercise of - * permissions under this License. - */ +/* Copyright 2021 Radix Publishing Ltd incorporated in Jersey (Channel Islands). +* +* Licensed under the Radix License, Version 1.0 (the "License"); you may not use this +* file except in compliance with the License. You may obtain a copy of the License at: +* +* radixfoundation.org/licenses/LICENSE-v1 +* +* The Licensor hereby grants permission for the Canonical version of the Work to be +* published, distributed and used under or by reference to the Licensor’s trademark +* Radix ® and use of any unregistered trade names, logos or get-up. +* +* The Licensor provides the Work (and each Contributor provides its Contributions) on an +* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, +* including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, +* MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. +* +* Whilst the Work is capable of being deployed, used and adopted (instantiated) to create +* a distributed ledger it is your responsibility to test and validate the code, together +* with all logic and performance of that code under all foreseeable scenarios. +* +* The Licensor does not make or purport to make and hereby excludes liability for all +* and any representation, warranty or undertaking in any form whatsoever, whether express +* or implied, to any entity or person, including any representation, warranty or +* undertaking, as to the functionality security use, value or other characteristics of +* any distributed ledger nor in respect the functioning or value of any tokens which may +* be created stored or transferred using the Work. The Licensor does not warrant that the +* Work or any use of the Work complies with any law or regulation in any territory where +* it may be implemented or used or that it will be appropriate for any specific purpose. +* +* Neither the licensor nor any current or former employees, officers, directors, partners, +* trustees, representatives, agents, advisors, contractors, or volunteers of the Licensor +* shall be liable for any direct or indirect, special, incidental, consequential or other +* losses of any kind, in tort, contract or otherwise (including but not limited to loss +* of revenue, income or profits, or loss of use or data, or loss of reputation, or loss +* of any economic or other opportunity of whatsoever nature or howsoever arising), arising +* out of or in connection with (without limitation of any use, misuse, of any ledger system +* or use made or its functionality or any performance or operation of any code or protocol +* caused by bugs or programming or logic errors or otherwise); +* +* A. any offer, purchase, holding, use, sale, exchange or transmission of any +* cryptographic keys, tokens or assets created, exchanged, stored or arising from any +* interaction with the Work; +* +* B. any failure in a transmission or loss of any token or assets keys or other digital +* artefacts due to errors in transmission; +* +* C. bugs, hacks, logic errors or faults in the Work or any communication; +* +* D. system software or apparatus including but not limited to losses caused by errors +* in holding or transmitting tokens by any third-party; +* +* E. breaches or failure of security including hacker attacks, loss or disclosure of +* password, loss of private key, unauthorised use or misuse of such passwords or keys; +* +* F. any losses including loss of anticipated savings or other benefits resulting from +* use of the Work or any changes to the Work (however implemented). +* +* You are solely responsible for; testing, validating and evaluation of all operation +* logic, functionality, security and appropriateness of using the Work for any commercial +* or non-commercial purpose and for any reproduction or redistribution by You of the +* Work. You assume all risks associated with Your use of the Work and the exercise of +* permissions under this License. +*/ using Dapper; using Microsoft.EntityFrameworkCore; diff --git a/src/RadixDlt.NetworkGateway.PostgresIntegration/ValueConverters/EntityAddressToStringConverter.cs b/src/RadixDlt.NetworkGateway.PostgresIntegration/ValueConverters/EntityAddressToStringConverter.cs index c318ab3b6..e06003cad 100644 --- a/src/RadixDlt.NetworkGateway.PostgresIntegration/ValueConverters/EntityAddressToStringConverter.cs +++ b/src/RadixDlt.NetworkGateway.PostgresIntegration/ValueConverters/EntityAddressToStringConverter.cs @@ -1,4 +1,4 @@ -/* Copyright 2021 Radix Publishing Ltd incorporated in Jersey (Channel Islands). +/* Copyright 2021 Radix Publishing Ltd incorporated in Jersey (Channel Islands). * * Licensed under the Radix License, Version 1.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at: diff --git a/tests/RadixDlt.NetworkGateway.UnitTests/PostgresIntegration/AccountDepositPreValidationTests.cs b/tests/RadixDlt.NetworkGateway.UnitTests/PostgresIntegration/AccountDepositPreValidationTests.cs index a574710a3..8f782eb64 100644 --- a/tests/RadixDlt.NetworkGateway.UnitTests/PostgresIntegration/AccountDepositPreValidationTests.cs +++ b/tests/RadixDlt.NetworkGateway.UnitTests/PostgresIntegration/AccountDepositPreValidationTests.cs @@ -141,5 +141,5 @@ public async Task AccountIsConfiguredToAllowExistings_AllResourceVaultsExists_De // Assert. result.AllowsTryDepositBatch.Should().BeTrue(); result.ResourceSpecificBehaviour.Should().BeEquivalentTo(expectedResourceSpecificBehaviour); - } + } }