Convert conformance tests to use java bindings (#17894)

This commit is contained in:
Andreas Triantafyllos 2023-11-29 17:34:06 +01:00 committed by GitHub
parent 38cd3cc724
commit b8eebc6ddd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
60 changed files with 2277 additions and 1510 deletions

View File

@ -881,7 +881,7 @@ scala_library(
],
unused_dependency_checker_mode = "error",
deps = [
":community_participant_admin-workflows-with-vacuuming_java.jar",
":community_participant_admin-workflows-with-vacuuming_java",
":pekko-stream-minus-patched-classes",
"//canton-3x:community_base",
"//canton-3x:community_common",

View File

@ -880,7 +880,7 @@ scala_library(
],
unused_dependency_checker_mode = "error",
deps = [
":community_participant_admin-workflows-with-vacuuming_java.jar",
":community_participant_admin-workflows-with-vacuuming_java",
":pekko-stream-minus-patched-classes",
"//canton:community_base",
"//canton:community_common",

View File

@ -396,14 +396,14 @@ EOF
)
dar_to_java(
name = "quickstart-model",
name = "quickstart-model-java",
src = "quickstart-model.dar",
package_prefix = "com.daml.quickstart.model",
)
java_binary(
name = "quickstart-java-lib",
srcs = glob(["source/app-dev/bindings-java/quickstart/template-root/src/main/java/**/*.java"]) + [":quickstart-model-srcjar"],
srcs = glob(["source/app-dev/bindings-java/quickstart/template-root/src/main/java/**/*.java"]) + [":quickstart-model-java-src.jar"],
main_class = "com.daml.quickstart.iou.IouMain",
deps = [
"//daml-lf/archive:daml_lf_dev_archive_proto_java",

View File

@ -111,7 +111,7 @@ da_scala_test_suite(
"@maven//:org_scalatestplus_scalacheck_1_15",
],
deps = [
":bindings-integration-tests-model-latest.jar",
":bindings-integration-tests-model-latest",
":bindings-java-tests-lib",
":bindings-rxjava",
"//language-support/java/bindings:bindings-java",

View File

@ -96,7 +96,7 @@ da_scala_test(
],
deps = [
":lib",
":test-daml-java.jar",
":test-daml-java",
"//bazel_tools/runfiles:scala_runfiles",
"//daml-lf/api-type-signature",
"//daml-lf/archive:daml_lf_archive_reader",
@ -211,7 +211,7 @@ scala_source_jar(
]),
test_class = "com.daml.testing.AllTestsFor%s" % mangle_for_java(target),
deps = [
":test-model-%s.jar" % target,
":test-model-%s" % target,
"//language-support/java/bindings:bindings-java",
"@maven//:com_google_protobuf_protobuf_java",
"@maven//:org_junit_jupiter_junit_jupiter_api",
@ -354,7 +354,7 @@ java_test(
),
test_class = "com.daml.AllTests",
deps = [
":integration-tests-model-%s.jar" % target,
":integration-tests-model-%s" % target,
"//language-support/java/bindings:bindings-java",
"@maven//:com_google_protobuf_protobuf_java",
"@maven//:org_junit_jupiter_junit_jupiter_api",
@ -407,7 +407,7 @@ da_scala_test(
],
tags = ["cpu:4"],
deps = [
":ledger-tests-model.jar",
":ledger-tests-model",
"//bazel_tools/runfiles:scala_runfiles",
"//daml-lf/data",
"//language-support/java/bindings:bindings-java",
@ -434,7 +434,7 @@ da_scala_benchmark_jmh(
srcs = glob(["src/bench/**/FromJsonBench.scala"]),
visibility = ["//visibility:public"],
deps = [
":test-model-2.dev.jar",
":test-model-2.dev",
"//language-support/java/bindings:bindings-java",
],
)
@ -444,7 +444,7 @@ da_scala_benchmark_jmh(
srcs = glob(["src/bench/**/ToJsonBench.scala"]),
visibility = ["//visibility:public"],
deps = [
":test-model-2.dev.jar",
":test-model-2.dev",
"//language-support/java/bindings:bindings-java",
],
)

View File

@ -1,6 +1,8 @@
# Copyright (c) 2023 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
load("//bazel_tools:pkg.bzl", "pkg_empty_zip")
load("//bazel_tools:pom_file.bzl", "pom_file")
load("//language-support/java:javaopts.bzl", "da_java_bindings_javacopts")
def mangle(name):
@ -13,17 +15,17 @@ def dar_to_java(**kwargs):
base_name = kwargs["name"]
dar = kwargs["src"]
visibility = kwargs.get("visibility", ["//visibility:private"])
src_out = base_name + "-srcs"
src_jar = base_name + "-srcjar"
lib = base_name + ".jar"
src_jar = base_name + "-src.jar"
package_prefix = kwargs.get("package_prefix", "")
native.genrule(
name = src_jar,
srcs = [dar],
outs = [mangle(src_jar)],
outs = [mangle(base_name) + ".srcjar"],
cmd = """
$(execpath //language-support/java/codegen:codegen) -o {gen_out} -d com.daml.ledger.javaapi.TestDecoder {gen_in}
$(JAVABASE)/bin/jar -cf $@ -C {gen_out} .
@ -36,7 +38,7 @@ def dar_to_java(**kwargs):
)
native.java_library(
name = lib,
name = base_name,
javacopts = da_java_bindings_javacopts,
srcs = [
":%s" % src_jar,
@ -44,8 +46,27 @@ def dar_to_java(**kwargs):
deps = [
"//language-support/java/bindings:bindings-java",
],
tags = kwargs.get("tags", []),
visibility = visibility,
)
# Create empty javadoc JAR for uploading proto jars to Maven Central
# we don't need to create an empty zip for sources, because dar_to_java
# creates a sources jar as a side effect automatically
pkg_empty_zip(
name = base_name + "_javadoc",
out = base_name + "_javadoc.jar",
)
if "tags" in kwargs:
for tag in kwargs["tags"]:
if tag.startswith("maven_coordinates="):
pom_file(
name = base_name + "_pom",
target = ":" + base_name,
)
break
test_exclusions = {
"1.6": ["src/it/daml/Tests/GenMapTest.daml", "src/it/daml/Tests/NumericTest.daml"],
"1.7": ["src/it/daml/Tests/GenMapTest.daml"],

View File

@ -21,7 +21,7 @@ load("//ledger-test-tool:conformance.bzl", "testtool_lf_versions")
visibility = ["//:__subpackages__"],
deps = [
"//daml-lf/data",
"//language-support/scala/bindings",
"//language-support/java/bindings:bindings-java",
"//ledger-api/grpc-definitions:ledger_api_proto_scala",
"//ledger/error",
"//ledger/ledger-api-errors",

View File

@ -4,7 +4,7 @@
package com.daml.ledger.api.testtool.infrastructure
import com.daml.ledger.api.testtool.infrastructure.participant.ParticipantTestContext
import com.daml.ledger.client.binding.Primitive.Party
import com.daml.ledger.javaapi.data.Party
object Allocation {

View File

@ -5,11 +5,24 @@ package com.daml.ledger.api.testtool.infrastructure
import com.daml.ledger.api.testtool.infrastructure.Allocation.{Participants, PartyAllocation}
import com.daml.ledger.api.testtool.infrastructure.participant.{Features, ParticipantTestContext}
import com.daml.ledger.javaapi.data.{Command, Party}
import com.daml.ledger.javaapi.data.{Identifier => JavaIdentifier}
import com.daml.lf.data.Ref
import com.daml.test.evidence.tag.EvidenceTag
import com.daml.ledger.api.v1.commands.Command.toJavaProto
import com.daml.ledger.api.v1.commands.{Command => CommandV1}
import com.daml.ledger.api.v1.value.Value.Sum
import com.daml.ledger.api.v1.value.{GenMap, Identifier, Optional, Value}
import com.daml.ledger.api.v1.value.{List => ListV1}
import com.daml.ledger.api.v1.value.{Map => MapV1}
import java.math.BigDecimal
import java.time.Instant
import java.util.{List => JList}
import scala.collection.mutable.ListBuffer
import scala.concurrent.{ExecutionContext, Future}
import scala.jdk.CollectionConverters._
import scala.language.implicitConversions
abstract class LedgerTestSuite {
private val testCaseBuffer: ListBuffer[LedgerTestCase] = ListBuffer()
@ -75,4 +88,71 @@ abstract class LedgerTestSuite {
}
def name: String = getClass.getSimpleName
def updateCommands(commands: JList[Command], f: CommandV1 => CommandV1): JList[Command] =
commands.asScala
.map(c => CommandV1.fromJavaProto(c.toProtoCommand))
.map(f)
.map(c => Command.fromProtoCommand(toJavaProto(c)))
.asJava
implicit class IdentifierConverter(id: JavaIdentifier) {
def toV1: Identifier = Identifier.fromJavaProto(id.toProto)
}
implicit def partyToString(party: Party): String = party.getValue
// TODO: when merged in canton (get it from ledger-common)
object TimestampConversion {
val MIN = Instant parse "0001-01-01T00:00:00Z"
val MAX = Instant parse "9999-12-31T23:59:59.999999Z"
}
object ClearIdsImplicits {
def clearIds(value: Value): Value = {
val sum = value.sum match {
case Sum.Record(record) =>
Sum.Record(
record.clearRecordId.copy(fields =
record.fields.map(f => f.copy(value = f.value.map(clearIds)))
)
)
case Sum.Variant(variant) =>
Sum.Variant(variant.clearVariantId.copy(value = variant.value.map(clearIds)))
case Sum.List(list) => Sum.List(ListV1(list.elements.map(clearIds)))
case Sum.Optional(optional) =>
Sum.Optional(Optional(optional.value.map(clearIds)))
case Sum.GenMap(genmap) =>
Sum.GenMap(GenMap(genmap.entries.map({ case GenMap.Entry(k, v) =>
GenMap.Entry(k.map(clearIds), v.map(clearIds))
})))
case Sum.Map(simplemap) =>
Sum.Map(MapV1(simplemap.entries.map({ case MapV1.Entry(k, v) =>
MapV1.Entry(k, v.map(clearIds))
})))
case _ => value.sum
}
Value(sum)
}
implicit class ClearValueIdsImplicits(record: com.daml.ledger.api.v1.value.Record) {
// TODO: remove when java bindings toValue produce an enriched Record w.r.t. type and field name
def clearValueIds: com.daml.ledger.api.v1.value.Record =
clearIds(Value(Sum.Record(record))).getRecord
}
}
object BigDecimalImplicits {
// TODO: when merged in canton (merge it w/ the corresponding BigDecimalImplicits)
implicit class IntToBigDecimal(value: Int) {
def toBigDecimal: BigDecimal = BigDecimal.valueOf(value.toLong)
}
implicit class DoubleToBigDecimal(value: Double) {
def toBigDecimal: BigDecimal = BigDecimal.valueOf(value)
}
}
}

View File

@ -6,7 +6,7 @@ package com.daml.ledger.api.testtool.infrastructure
import com.daml.ledger.api.testtool.infrastructure.Assertions._
import com.daml.ledger.api.testtool.infrastructure.participant.ParticipantTestContext
import com.daml.ledger.api.v1.transaction.TransactionTree
import com.daml.ledger.client.binding.Primitive
import com.daml.ledger.javaapi.data.Party
import com.daml.lf.data.{Bytes, Ref}
import com.daml.timer.Delayed
@ -45,7 +45,7 @@ private[testtool] object RaceConditionTests {
def transactions(
ledger: ParticipantTestContext,
party: Primitive.Party,
party: Party,
waitBefore: FiniteDuration = WaitBeforeGettingTransactions,
)(implicit ec: ExecutionContext): Future[Vector[TransactionTree]] =
Delayed.by(waitBefore)(()).flatMap(_ => ledger.transactionTrees(party))

View File

@ -3,10 +3,10 @@
package com.daml.ledger.api.testtool.infrastructure
import com.daml.ledger.api.refinements.ApiTypes.Party
import com.daml.ledger.api.testtool.infrastructure.Eventually.eventually
import com.daml.ledger.api.testtool.infrastructure.participant.ParticipantTestContext
import com.daml.ledger.client.binding.Primitive
import com.daml.ledger.javaapi.data.Party
import com.daml.ledger.javaapi.data.codegen.ContractId
import scala.concurrent.{ExecutionContext, Future}
@ -36,15 +36,15 @@ object Synchronize {
// point before invoking this method
}
final def waitForContract[T](
final def waitForContract[TCid <: ContractId[?]](
participant: ParticipantTestContext,
party: Party,
contractId: Primitive.ContractId[T],
contractId: TCid,
)(implicit ec: ExecutionContext): Future[Unit] =
eventually("Wait for contract to become active") {
participant.activeContracts(party).map { events =>
assert(
events.exists(_.contractId == contractId.toString),
events.exists(_.contractId == contractId.contractId),
s"Could not find contract $contractId",
)
}

View File

@ -4,8 +4,6 @@
package com.daml.ledger.api.testtool.infrastructure.assertions
import java.time.Duration
import com.daml.api.util.DurationConversion
import com.daml.ledger.api.testtool.infrastructure.Assertions.{assertDefined, fail}
import com.daml.ledger.api.testtool.infrastructure.WithTimeout
import com.daml.ledger.api.testtool.infrastructure.participant.ParticipantTestContext
@ -15,7 +13,7 @@ import com.daml.ledger.api.v1.experimental_features.CommandDeduplicationPeriodSu
OffsetSupport,
}
import com.daml.ledger.api.v1.ledger_offset.LedgerOffset
import com.daml.ledger.client.binding.Primitive.Party
import com.daml.ledger.javaapi.data.Party
import com.daml.lf.data.Ref
import com.google.protobuf.duration.{Duration => DurationProto}
import io.grpc.Status.Code
@ -164,4 +162,14 @@ object CommandDeduplicationAssertions {
case OffsetSupport.Unrecognized(_) | OffsetSupport.OFFSET_NOT_SUPPORTED =>
fail("Deduplication offsets are not supported")
}
object DurationConversion {
def toProto(jDuration: Duration): DurationProto =
DurationProto(jDuration.getSeconds, jDuration.getNano)
def fromProto(pDuration: DurationProto): Duration =
Duration.ofSeconds(pDuration.seconds, pDuration.nanos.toLong)
}
}

View File

@ -4,9 +4,8 @@
package com.daml.ledger.api.testtool.infrastructure.participant
import com.daml.error.ErrorCode
import java.time.Instant
import com.daml.ledger.api.refinements.ApiTypes.TemplateId
import java.time.Instant
import com.daml.ledger.api.testtool.infrastructure.Endpoint
import com.daml.ledger.api.testtool.infrastructure.participant.ParticipantTestContext.{
CompletionResponse,
@ -52,7 +51,6 @@ import com.daml.ledger.api.v1.command_service.{
SubmitAndWaitRequest,
}
import com.daml.ledger.api.v1.command_submission_service.SubmitRequest
import com.daml.ledger.api.v1.commands.Command
import com.daml.ledger.api.v1.completion.Completion
import com.daml.ledger.api.v1.event.CreatedEvent
import com.daml.ledger.api.v1.ledger_configuration_service.LedgerConfiguration
@ -72,13 +70,14 @@ import com.daml.ledger.api.v1.transaction_service.{
GetTransactionsRequest,
GetTransactionsResponse,
}
import com.daml.ledger.api.v1.value.Value
import com.daml.ledger.client.binding.{Primitive, Template}
import com.daml.ledger.javaapi.data.{Command, Identifier, Party, Template, Value, Unit => UnitData}
import com.daml.ledger.javaapi.data.codegen.{ContractCompanion, ContractId, Exercised, Update}
import com.daml.lf.data.Ref.HexString
import com.google.protobuf.ByteString
import io.grpc.health.v1.health.HealthCheckResponse
import io.grpc.stub.StreamObserver
import java.util.{List => JList}
import scala.concurrent.{ExecutionContext, Future}
trait ParticipantTestContext extends UserManagementTestContext {
@ -141,7 +140,7 @@ trait ParticipantTestContext extends UserManagementTestContext {
/** Managed version of party allocation, should be used anywhere a party has
* to be allocated unless the party management service itself is under test
*/
def allocateParty(): Future[Primitive.Party]
def allocateParty(): Future[Party]
/** Non managed version of party allocation. Use exclusively when testing the party management service.
*/
@ -150,47 +149,47 @@ trait ParticipantTestContext extends UserManagementTestContext {
displayName: Option[String] = None,
localMetadata: Option[ObjectMeta] = None,
identityProviderId: Option[String] = None,
): Future[Primitive.Party]
): Future[Party]
def allocateParty(req: AllocatePartyRequest): Future[AllocatePartyResponse]
def updatePartyDetails(req: UpdatePartyDetailsRequest): Future[UpdatePartyDetailsResponse]
def updatePartyIdentityProviderId(
request: UpdatePartyIdentityProviderRequest
): Future[UpdatePartyIdentityProviderResponse]
def allocateParties(n: Int): Future[Vector[Primitive.Party]]
def allocateParties(n: Int): Future[Vector[Party]]
def getParties(req: GetPartiesRequest): Future[GetPartiesResponse]
def getParties(parties: Seq[Primitive.Party]): Future[Seq[PartyDetails]]
def listKnownParties(): Future[Set[Primitive.Party]]
def getParties(parties: Seq[Party]): Future[Seq[PartyDetails]]
def listKnownParties(): Future[Set[Party]]
def listKnownPartiesResp(): Future[ListKnownPartiesResponse]
/** @return a future that completes when all the participants can list all the expected parties
*/
def waitForParties(
otherParticipants: Iterable[ParticipantTestContext],
expectedParties: Set[Primitive.Party],
expectedParties: Set[Party],
): Future[Unit]
def activeContracts(
request: GetActiveContractsRequest
): Future[(Option[LedgerOffset], Vector[CreatedEvent])]
def activeContractsIds(
request: GetActiveContractsRequest
): Future[(Option[LedgerOffset], Vector[Primitive.ContractId[Any]])] = {
): Future[(Option[LedgerOffset], Vector[ContractId[Any]])] = {
activeContracts(request).map { case (offset, createEvents: Seq[CreatedEvent]) =>
(offset, createEvents.map(c => Primitive.ContractId[Any](c.contractId)))
(offset, createEvents.map(c => new ContractId[Any](c.contractId)))
}
}
def activeContractsRequest(
parties: Seq[Primitive.Party],
templateIds: Seq[TemplateId] = Seq.empty,
interfaceFilters: Seq[(TemplateId, IncludeInterfaceView)] = Seq.empty,
parties: Seq[Party],
templateIds: Seq[Identifier] = Seq.empty,
interfaceFilters: Seq[(Identifier, IncludeInterfaceView)] = Seq.empty,
activeAtOffset: String = "",
useTemplateIdBasedLegacyFormat: Boolean = true,
): GetActiveContractsRequest
def activeContracts(parties: Primitive.Party*): Future[Vector[CreatedEvent]]
def activeContracts(parties: Party*): Future[Vector[CreatedEvent]]
def activeContractsByTemplateId(
templateIds: Seq[TemplateId],
parties: Primitive.Party*
templateIds: Seq[Identifier],
parties: Party*
): Future[Vector[CreatedEvent]]
/** Create a [[TransactionFilter]] with a set of [[Party]] objects.
@ -199,15 +198,15 @@ trait ParticipantTestContext extends UserManagementTestContext {
* directly pass a set of [[Party]]
*/
def transactionFilter(
parties: Seq[Primitive.Party],
templateIds: Seq[TemplateId] = Seq.empty,
interfaceFilters: Seq[(TemplateId, IncludeInterfaceView)] = Seq.empty,
parties: Seq[Party],
templateIds: Seq[Identifier] = Seq.empty,
interfaceFilters: Seq[(Identifier, IncludeInterfaceView)] = Seq.empty,
useTemplateIdBasedLegacyFormat: Boolean = true,
): TransactionFilter
def filters(
templateIds: Seq[TemplateId] = Seq.empty,
interfaceFilters: Seq[(TemplateId, IncludeInterfaceView)] = Seq.empty,
templateIds: Seq[Identifier] = Seq.empty,
interfaceFilters: Seq[(Identifier, IncludeInterfaceView)] = Seq.empty,
useTemplateIdBasedLegacyFormat: Boolean = true,
): Filters
@ -221,8 +220,8 @@ trait ParticipantTestContext extends UserManagementTestContext {
responseObserver: StreamObserver[GetTransactionsResponse],
): Unit
def flatTransactionsByTemplateId(
templateId: TemplateId,
parties: Primitive.Party*
templateId: Identifier,
parties: Party*
): Future[Vector[Transaction]]
/** Non-managed version of [[flatTransactions]], use this only if you need to tweak the request (i.e. to test low-level details)
@ -231,7 +230,7 @@ trait ParticipantTestContext extends UserManagementTestContext {
/** Managed version of [[flatTransactions]], use this unless you need to tweak the request (i.e. to test low-level details)
*/
def flatTransactions(parties: Primitive.Party*): Future[Vector[Transaction]]
def flatTransactions(parties: Party*): Future[Vector[Transaction]]
/** Non-managed version of [[flatTransactions]], use this only if you need to tweak the request (i.e. to test low-level details)
*/
@ -239,10 +238,10 @@ trait ParticipantTestContext extends UserManagementTestContext {
/** Managed version of [[flatTransactions]], use this unless you need to tweak the request (i.e. to test low-level details)
*/
def flatTransactions(take: Int, parties: Primitive.Party*): Future[Vector[Transaction]]
def flatTransactions(take: Int, parties: Party*): Future[Vector[Transaction]]
def transactionTreesByTemplateId(
templateId: TemplateId,
parties: Primitive.Party*
templateId: Identifier,
parties: Party*
): Future[Vector[TransactionTree]]
/** Non-managed version of [[transactionTrees]], use this only if you need to tweak the request (i.e. to test low-level details)
@ -251,7 +250,7 @@ trait ParticipantTestContext extends UserManagementTestContext {
/** Managed version of [[transactionTrees]], use this unless you need to tweak the request (i.e. to test low-level details)
*/
def transactionTrees(parties: Primitive.Party*): Future[Vector[TransactionTree]]
def transactionTrees(parties: Party*): Future[Vector[TransactionTree]]
/** Non-managed version of [[transactionTrees]], use this only if you need to tweak the request (i.e. to test low-level details)
*/
@ -262,7 +261,7 @@ trait ParticipantTestContext extends UserManagementTestContext {
/** Managed version of [[transactionTrees]], use this unless you need to tweak the request (i.e. to test low-level details)
*/
def transactionTrees(take: Int, parties: Primitive.Party*): Future[Vector[TransactionTree]]
def transactionTrees(take: Int, parties: Party*): Future[Vector[TransactionTree]]
/** Create a [[GetTransactionByIdRequest]] with an identifier and a set of [[Party]] objects.
* You should use this only when you need to tweak the request of [[transactionTreeById]] or
@ -271,7 +270,7 @@ trait ParticipantTestContext extends UserManagementTestContext {
*/
def getTransactionByIdRequest(
transactionId: String,
parties: Seq[Primitive.Party],
parties: Seq[Party],
): GetTransactionByIdRequest
/** Non-managed version of [[transactionTreeById]], use this only if you need to tweak the request (i.e. to test low-level details)
@ -280,7 +279,7 @@ trait ParticipantTestContext extends UserManagementTestContext {
/** Managed version of [[transactionTrees]], use this unless you need to tweak the request (i.e. to test low-level details)
*/
def transactionTreeById(transactionId: String, parties: Primitive.Party*): Future[TransactionTree]
def transactionTreeById(transactionId: String, parties: Party*): Future[TransactionTree]
/** Non-managed version of [[flatTransactionById]], use this only if you need to tweak the request (i.e. to test low-level details)
*/
@ -288,7 +287,7 @@ trait ParticipantTestContext extends UserManagementTestContext {
/** Managed version of [[flatTransactionById]], use this unless you need to tweak the request (i.e. to test low-level details)
*/
def flatTransactionById(transactionId: String, parties: Primitive.Party*): Future[Transaction]
def flatTransactionById(transactionId: String, parties: Party*): Future[Transaction]
/** Create a [[GetTransactionByEventIdRequest]] with an identifier and a set of [[Party]] objects.
* You should use this only when you need to tweak the request of [[transactionTreeByEventId]] or
@ -297,7 +296,7 @@ trait ParticipantTestContext extends UserManagementTestContext {
*/
def getTransactionByEventIdRequest(
eventId: String,
parties: Seq[Primitive.Party],
parties: Seq[Party],
): GetTransactionByEventIdRequest
/** Non-managed version of [[transactionTreeByEventId]], use this only if you need to tweak the request (i.e. to test low-level details)
@ -306,7 +305,7 @@ trait ParticipantTestContext extends UserManagementTestContext {
/** Managed version of [[transactionTreeByEventId]], use this unless you need to tweak the request (i.e. to test low-level details)
*/
def transactionTreeByEventId(eventId: String, parties: Primitive.Party*): Future[TransactionTree]
def transactionTreeByEventId(eventId: String, parties: Party*): Future[TransactionTree]
/** Non-managed version of [[flatTransactionByEventId]], use this only if you need to tweak the request (i.e. to test low-level details)
*/
@ -314,7 +313,7 @@ trait ParticipantTestContext extends UserManagementTestContext {
/** Managed version of [[flatTransactionByEventId]], use this unless you need to tweak the request (i.e. to test low-level details)
*/
def flatTransactionByEventId(eventId: String, parties: Primitive.Party*): Future[Transaction]
def flatTransactionByEventId(eventId: String, parties: Party*): Future[Transaction]
def getEventsByContractId(
request: GetEventsByContractIdRequest
@ -324,55 +323,62 @@ trait ParticipantTestContext extends UserManagementTestContext {
request: GetEventsByContractKeyRequest
): Future[GetEventsByContractKeyResponse]
def create[T](
party: Primitive.Party,
template: Template[T],
): Future[Primitive.ContractId[T]]
def create[T](
actAs: List[Primitive.Party],
readAs: List[Primitive.Party],
template: Template[T],
): Future[Primitive.ContractId[T]]
def createAndGetTransactionId[T](
party: Primitive.Party,
template: Template[T],
): Future[(String, Primitive.ContractId[T])]
def create[
TCid <: ContractId[T],
T <: Template,
](
party: Party,
template: T,
)(implicit companion: ContractCompanion[?, TCid, T]): Future[TCid]
def create[TCid <: ContractId[T], T <: Template](
actAs: List[Party],
readAs: List[Party],
template: T,
)(implicit companion: ContractCompanion[?, TCid, T]): Future[TCid]
def createAndGetTransactionId[TCid <: ContractId[T], T <: Template](
party: Party,
template: T,
)(implicit companion: ContractCompanion[?, TCid, T]): Future[(String, TCid)]
def exercise[T](
party: Primitive.Party,
exercise: Primitive.Update[T],
party: Party,
exercise: Update[T],
): Future[TransactionTree]
def exercise[T](
actAs: List[Primitive.Party],
readAs: List[Primitive.Party],
exercise: Primitive.Update[T],
actAs: List[Party],
readAs: List[Party],
exercise: Update[T],
): Future[TransactionTree]
def exerciseForFlatTransaction[T](
party: Primitive.Party,
exercise: Primitive.Update[T],
party: Party,
exercise: Update[T],
): Future[Transaction]
def exerciseAndGetContract[T](
party: Primitive.Party,
exercise: Primitive.Update[Any],
): Future[Primitive.ContractId[T]]
def exerciseByKey[T](
party: Primitive.Party,
template: Primitive.TemplateId[T],
def exerciseAndGetContract[TCid <: ContractId[T], T]( // TODO: Check if T is not needed
party: Party,
exercise: Update[Exercised[TCid]],
)(implicit companion: ContractCompanion[?, TCid, T]): Future[TCid]
def exerciseAndGetContractNoDisclose[TCid <: ContractId[?]]( // TODO: rename??
party: Party,
exercise: Update[Exercised[UnitData]],
)(implicit companion: ContractCompanion[?, TCid, ?]): Future[TCid]
def exerciseByKey(
party: Party,
template: Identifier,
key: Value,
choice: String,
argument: Value,
): Future[TransactionTree]
def submitRequest(
actAs: List[Primitive.Party],
readAs: List[Primitive.Party],
commands: Command*
actAs: List[Party],
readAs: List[Party],
commands: JList[Command],
): SubmitRequest
def submitRequest(party: Primitive.Party, commands: Command*): SubmitRequest
def submitRequest(party: Party, commands: JList[Command] = JList.of()): SubmitRequest
def submitAndWaitRequest(
actAs: List[Primitive.Party],
readAs: List[Primitive.Party],
commands: Command*
actAs: List[Party],
readAs: List[Party],
commands: JList[Command],
): SubmitAndWaitRequest
def submitAndWaitRequest(party: Primitive.Party, commands: Command*): SubmitAndWaitRequest
def submitAndWaitRequest(party: Party, commands: JList[Command]): SubmitAndWaitRequest
def submit(request: SubmitRequest): Future[Unit]
def submitAndWait(request: SubmitAndWaitRequest): Future[Unit]
def submitAndWaitForTransactionId(
@ -389,7 +395,7 @@ trait ParticipantTestContext extends UserManagementTestContext {
submitAndWaitGeneric: ParticipantTestContext => Future[T],
): Future[T]
def completionStreamRequest(from: LedgerOffset = referenceOffset)(
parties: Primitive.Party*
parties: Party*
): CompletionStreamRequest
def completionEnd(request: CompletionEndRequest): Future[CompletionEndResponse]
def completionStream(
@ -397,25 +403,25 @@ trait ParticipantTestContext extends UserManagementTestContext {
streamObserver: StreamObserver[CompletionStreamResponse],
): Unit
def firstCompletions(request: CompletionStreamRequest): Future[Vector[Completion]]
def firstCompletions(parties: Primitive.Party*): Future[Vector[Completion]]
def firstCompletions(parties: Party*): Future[Vector[Completion]]
def findCompletionAtOffset(
offset: HexString,
p: Completion => Boolean,
)(parties: Primitive.Party*): Future[Option[CompletionResponse]]
)(parties: Party*): Future[Option[CompletionResponse]]
def findCompletion(
request: CompletionStreamRequest
)(p: Completion => Boolean): Future[Option[CompletionResponse]]
def findCompletion(parties: Primitive.Party*)(
def findCompletion(parties: Party*)(
p: Completion => Boolean
): Future[Option[CompletionResponse]]
def checkpoints(n: Int, request: CompletionStreamRequest): Future[Vector[Checkpoint]]
def checkpoints(n: Int, from: LedgerOffset = referenceOffset)(
parties: Primitive.Party*
parties: Party*
): Future[Vector[Checkpoint]]
def firstCheckpoint(request: CompletionStreamRequest): Future[Checkpoint]
def firstCheckpoint(parties: Primitive.Party*): Future[Checkpoint]
def firstCheckpoint(parties: Party*): Future[Checkpoint]
def nextCheckpoint(request: CompletionStreamRequest): Future[Checkpoint]
def nextCheckpoint(from: LedgerOffset, parties: Primitive.Party*): Future[Checkpoint]
def nextCheckpoint(from: LedgerOffset, parties: Party*): Future[Checkpoint]
def configuration(overrideLedgerId: Option[String] = None): Future[LedgerConfiguration]
def checkHealth(): Future[HealthCheckResponse]
def watchHealth(): Future[Seq[HealthCheckResponse]]
@ -438,7 +444,7 @@ trait ParticipantTestContext extends UserManagementTestContext {
private[infrastructure] def preallocateParties(
n: Int,
participants: Iterable[ParticipantTestContext],
): Future[Vector[Primitive.Party]]
): Future[Vector[Party]]
def prune(
pruneUpTo: LedgerOffset,
@ -453,8 +459,8 @@ trait ParticipantTestContext extends UserManagementTestContext {
*/
def pruneCantonSafe(
pruneUpTo: LedgerOffset,
party: Primitive.Party,
dummyCommand: Primitive.Party => Command,
party: Party,
dummyCommand: Party => JList[Command],
pruneAllDivulgedContracts: Boolean = false,
)(implicit ec: ExecutionContext): Future[Unit]

View File

@ -4,10 +4,9 @@
package com.daml.ledger.api.testtool.infrastructure.participant
import com.daml.error.ErrorCode
import java.time.{Clock, Instant}
import com.daml.grpc.test.StreamConsumer
import com.daml.ledger.api.refinements.ApiTypes.TemplateId
import com.daml.ledger.api.testtool.infrastructure.Eventually.eventually
import com.daml.ledger.api.testtool.infrastructure.ProtobufConverters._
import com.daml.ledger.api.testtool.infrastructure.participant.ParticipantTestContext.{
@ -27,6 +26,7 @@ import com.daml.ledger.api.testtool.infrastructure.{
LedgerServices,
PartyAllocationConfiguration,
}
import com.daml.ledger.api.v1.{value => v1}
import com.daml.ledger.api.v1.active_contracts_service.{
GetActiveContractsRequest,
GetActiveContractsResponse,
@ -73,7 +73,7 @@ import com.daml.ledger.api.v1.command_service.{
SubmitAndWaitRequest,
}
import com.daml.ledger.api.v1.command_submission_service.SubmitRequest
import com.daml.ledger.api.v1.commands.{Command, Commands, ExerciseByKeyCommand}
import com.daml.ledger.api.v1.commands.{Commands, Command => ApiCommand}
import com.daml.ledger.api.v1.completion.Completion
import com.daml.ledger.api.v1.event.Event.Event.Created
import com.daml.ledger.api.v1.event.{CreatedEvent, Event}
@ -107,9 +107,16 @@ import com.daml.ledger.api.v1.transaction_service.{
GetTransactionsRequest,
GetTransactionsResponse,
}
import com.daml.ledger.api.v1.value.Value
import com.daml.ledger.client.binding.Primitive.Party
import com.daml.ledger.client.binding.{Primitive, Template}
import com.daml.ledger.javaapi.data.{
Command,
ExerciseByKeyCommand,
Identifier,
Party,
Template,
Value,
Unit => UnitData,
}
import com.daml.ledger.javaapi.data.codegen.{ContractCompanion, ContractId, Exercised, Update}
import com.daml.lf.data.Ref
import com.daml.logging.{ContextualizedLogger, LoggingContext}
import com.daml.timer.Delayed
@ -118,11 +125,11 @@ import io.grpc.StatusRuntimeException
import io.grpc.health.v1.health.{HealthCheckRequest, HealthCheckResponse}
import io.grpc.protobuf.StatusProto
import io.grpc.stub.StreamObserver
import scalaz.Tag
import scalaz.syntax.tag._
import java.util.{List => JList}
import scala.concurrent.duration.DurationInt
import scala.concurrent.{ExecutionContext, Future}
import scala.jdk.CollectionConverters._
import scala.util.{Failure, Success}
import scala.util.control.NonFatal
@ -245,7 +252,7 @@ final class SingleParticipantTestContext private[participant] (
override def allocateParty(): Future[Party] =
services.partyManagement
.allocateParty(new AllocatePartyRequest(partyIdHint = nextPartyHintId()))
.map(r => Party(r.partyDetails.get.party))
.map(r => new Party(r.partyDetails.get.party))
override def allocateParty(
partyIdHint: Option[String] = None,
@ -262,7 +269,7 @@ final class SingleParticipantTestContext private[participant] (
identityProviderId = identityProviderId.getOrElse(""),
)
)
.map(r => Party(r.partyDetails.get.party))
.map(r => new Party(r.partyDetails.get.party))
override def allocateParty(req: AllocatePartyRequest): Future[AllocatePartyResponse] =
services.partyManagement
@ -287,13 +294,13 @@ final class SingleParticipantTestContext private[participant] (
override def getParties(parties: Seq[Party]): Future[Seq[PartyDetails]] =
services.partyManagement
.getParties(GetPartiesRequest(parties.map(_.unwrap)))
.getParties(GetPartiesRequest(parties.map(_.getValue)))
.map(_.partyDetails)
override def listKnownParties(): Future[Set[Party]] =
services.partyManagement
.listKnownParties(new ListKnownPartiesRequest())
.map(_.partyDetails.map(partyDetails => Party(partyDetails.party)).toSet)
.map(_.partyDetails.map(partyDetails => new Party(partyDetails.party)).toSet)
override def listKnownPartiesResp(): Future[ListKnownPartiesResponse] =
services.partyManagement
@ -336,8 +343,8 @@ final class SingleParticipantTestContext private[participant] (
override def activeContractsRequest(
parties: Seq[Party],
templateIds: Seq[TemplateId] = Seq.empty,
interfaceFilters: Seq[(TemplateId, IncludeInterfaceView)] = Seq.empty,
templateIds: Seq[Identifier] = Seq.empty,
interfaceFilters: Seq[(Identifier, IncludeInterfaceView)] = Seq.empty,
activeAtOffset: String = "",
useTemplateIdBasedLegacyFormat: Boolean = true,
): GetActiveContractsRequest =
@ -354,7 +361,7 @@ final class SingleParticipantTestContext private[participant] (
activeContractsByTemplateId(Seq.empty, parties: _*)
override def activeContractsByTemplateId(
templateIds: Seq[TemplateId],
templateIds: Seq[Identifier],
parties: Party*
): Future[Vector[CreatedEvent]] =
activeContracts(
@ -367,21 +374,21 @@ final class SingleParticipantTestContext private[participant] (
def transactionFilter(
parties: Seq[Party],
templateIds: Seq[TemplateId] = Seq.empty,
interfaceFilters: Seq[(TemplateId, IncludeInterfaceView)] = Seq.empty,
templateIds: Seq[Identifier] = Seq.empty,
interfaceFilters: Seq[(Identifier, IncludeInterfaceView)] = Seq.empty,
useTemplateIdBasedLegacyFormat: Boolean = true,
): TransactionFilter =
new TransactionFilter(
parties
.map(party =>
party.unwrap -> filters(templateIds, interfaceFilters, useTemplateIdBasedLegacyFormat)
party.getValue -> filters(templateIds, interfaceFilters, useTemplateIdBasedLegacyFormat)
)
.toMap
)
override def filters(
templateIds: Seq[TemplateId] = Seq.empty,
interfaceFilters: Seq[(TemplateId, IncludeInterfaceView)] = Seq.empty,
templateIds: Seq[Identifier] = Seq.empty,
interfaceFilters: Seq[(Identifier, IncludeInterfaceView)] = Seq.empty,
useTemplateIdBasedLegacyFormat: Boolean = true,
): Filters = new Filters(
if (templateIds.isEmpty && interfaceFilters.isEmpty) None
@ -389,17 +396,27 @@ final class SingleParticipantTestContext private[participant] (
Some(
new InclusiveFilters(
templateIds =
if (useTemplateIdBasedLegacyFormat) templateIds.map(Tag.unwrap).toSeq
if (useTemplateIdBasedLegacyFormat)
templateIds
.map(id => v1.Identifier.fromJavaProto(id.toProto))
.toSeq
else scala.Seq.empty,
interfaceFilters = interfaceFilters.map { case (id, includeInterfaceView) =>
new InterfaceFilter(
Some(Tag.unwrap(id)),
Some(v1.Identifier.fromJavaProto(id.toProto)),
includeInterfaceView = includeInterfaceView,
)
}.toSeq,
templateFilters =
if (!useTemplateIdBasedLegacyFormat)
templateIds.map(tid => new TemplateFilter(Some(Tag.unwrap(tid)), false)).toSeq
templateIds
.map(tid =>
new TemplateFilter(
Some(v1.Identifier.fromJavaProto(tid.toProto)),
false,
)
)
.toSeq
else
scala.Seq.empty,
)
@ -437,7 +454,7 @@ final class SingleParticipantTestContext private[participant] (
services.transaction.getTransactions(request, responseObserver)
override def flatTransactionsByTemplateId(
templateId: TemplateId,
templateId: Identifier,
parties: Party*
): Future[Vector[Transaction]] =
flatTransactions(getTransactionsRequest(transactionFilter(parties, Seq(templateId))))
@ -460,7 +477,7 @@ final class SingleParticipantTestContext private[participant] (
flatTransactions(take, getTransactionsRequest(transactionFilter(parties)))
override def transactionTreesByTemplateId(
templateId: TemplateId,
templateId: Identifier,
parties: Party*
): Future[Vector[TransactionTree]] =
transactionTrees(getTransactionsRequest(transactionFilter(parties, Seq(templateId))))
@ -486,7 +503,7 @@ final class SingleParticipantTestContext private[participant] (
transactionId: String,
parties: Seq[Party],
): GetTransactionByIdRequest =
new GetTransactionByIdRequest(ledgerId, transactionId, Tag.unsubst(parties))
new GetTransactionByIdRequest(ledgerId, transactionId, parties.map(_.getValue))
override def transactionTreeById(request: GetTransactionByIdRequest): Future[TransactionTree] =
services.transaction.getTransactionById(request).map(_.getTransaction)
@ -507,7 +524,7 @@ final class SingleParticipantTestContext private[participant] (
eventId: String,
parties: Seq[Party],
): GetTransactionByEventIdRequest =
new GetTransactionByEventIdRequest(ledgerId, eventId, Tag.unsubst(parties))
new GetTransactionByEventIdRequest(ledgerId, eventId, parties.map(_.getValue))
override def transactionTreeByEventId(
request: GetTransactionByEventIdRequest
@ -527,9 +544,11 @@ final class SingleParticipantTestContext private[participant] (
override def flatTransactionByEventId(eventId: String, parties: Party*): Future[Transaction] =
flatTransactionByEventId(getTransactionByEventIdRequest(eventId, parties))
private def extractContracts[T](transaction: Transaction): Seq[Primitive.ContractId[T]] =
private def extractContracts[TCid <: ContractId[?]](transaction: Transaction)(implicit
companion: ContractCompanion[?, TCid, ?]
): Seq[TCid] =
transaction.events.collect { case Event(Created(e)) =>
Primitive.ContractId(e.contractId)
companion.toContractId(new ContractId(e.contractId))
}
override def getEventsByContractId(
@ -542,77 +561,93 @@ final class SingleParticipantTestContext private[participant] (
): Future[GetEventsByContractKeyResponse] =
services.eventQuery.getEventsByContractKey(request)
override def create[T](
override def create[
TCid <: ContractId[T],
T <: Template,
](
party: Party,
template: Template[T],
): Future[Primitive.ContractId[T]] =
template: T,
)(implicit companion: ContractCompanion[?, TCid, T]): Future[TCid] =
submitAndWaitForTransaction(
submitAndWaitRequest(party, template.create.command)
submitAndWaitRequest(party, template.create.commands)
)
.map(response => extractContracts(response.getTransaction).head)
override def create[T](
override def create[TCid <: ContractId[T], T <: Template](
actAs: List[Party],
readAs: List[Party],
template: Template[T],
): Future[Primitive.ContractId[T]] =
template: T,
)(implicit companion: ContractCompanion[?, TCid, T]): Future[TCid] =
submitAndWaitForTransaction(
submitAndWaitRequest(actAs, readAs, template.create.command)
submitAndWaitRequest(actAs, readAs, template.create.commands)
).map(response => extractContracts(response.getTransaction).head)
override def createAndGetTransactionId[T](
override def createAndGetTransactionId[TCid <: ContractId[
T
], T <: Template](
party: Party,
template: Template[T],
): Future[(String, Primitive.ContractId[T])] =
template: T,
)(implicit companion: ContractCompanion[?, TCid, T]): Future[(String, TCid)] =
submitAndWaitForTransaction(
submitAndWaitRequest(party, template.create.command)
submitAndWaitRequest(party, template.create.commands)
)
.map(_.getTransaction)
.map(tx =>
tx.transactionId -> tx.events.collect { case Event(Created(e)) =>
Primitive.ContractId(e.contractId)
companion.toContractId(new ContractId(e.contractId))
}.head
)
override def exercise[T](
party: Party,
exercise: Primitive.Update[T],
exercise: Update[T],
): Future[TransactionTree] =
submitAndWaitForTransactionTree(
submitAndWaitRequest(party, exercise.command)
submitAndWaitRequest(party, exercise.commands)
).map(_.getTransaction)
override def exercise[T](
actAs: List[Party],
readAs: List[Party],
exercise: Primitive.Update[T],
exercise: Update[T],
): Future[TransactionTree] =
submitAndWaitForTransactionTree(
submitAndWaitRequest(actAs, readAs, exercise.command)
submitAndWaitRequest(actAs, readAs, exercise.commands)
).map(_.getTransaction)
override def exerciseForFlatTransaction[T](
party: Party,
exercise: Primitive.Update[T],
exercise: Update[T],
): Future[Transaction] =
submitAndWaitForTransaction(
submitAndWaitRequest(party, exercise.command)
submitAndWaitRequest(party, exercise.commands)
).map(_.getTransaction)
override def exerciseAndGetContract[T](
override def exerciseAndGetContract[TCid <: ContractId[T], T](
party: Party,
exercise: Primitive.Update[Any],
): Future[Primitive.ContractId[T]] =
exercise: Update[Exercised[TCid]],
)(implicit companion: ContractCompanion[?, TCid, T]): Future[TCid] =
submitAndWaitForTransaction(
submitAndWaitRequest(party, exercise.command)
submitAndWaitRequest(party, exercise.commands)
)
.map(_.getTransaction)
.map(extractContracts)
.map(_.head.asInstanceOf[Primitive.ContractId[T]])
.map(t => extractContracts(t)(companion))
.map(_.head)
override def exerciseByKey[T](
override def exerciseAndGetContractNoDisclose[TCid <: ContractId[?]](
party: Party,
template: Primitive.TemplateId[T],
exercise: Update[Exercised[UnitData]],
)(implicit companion: ContractCompanion[?, TCid, ?]): Future[TCid] =
submitAndWaitForTransaction(
submitAndWaitRequest(party, exercise.commands)
)
.map(_.getTransaction)
.map(t => extractContracts(t)(companion))
.map(_.head)
override def exerciseByKey(
party: Party,
template: Identifier,
key: Value,
choice: String,
argument: Value,
@ -620,14 +655,12 @@ final class SingleParticipantTestContext private[participant] (
submitAndWaitForTransactionTree(
submitAndWaitRequest(
party,
Command.of(
Command.Command.ExerciseByKey(
ExerciseByKeyCommand(
Some(template.unwrap),
Option(key),
choice,
Option(argument),
)
JList.of(
new ExerciseByKeyCommand(
template,
key,
choice,
argument,
)
),
)
@ -636,7 +669,7 @@ final class SingleParticipantTestContext private[participant] (
override def submitRequest(
actAs: List[Party],
readAs: List[Party],
commands: Command*
commands: JList[Command],
): SubmitRequest =
new SubmitRequest(
Some(
@ -645,15 +678,15 @@ final class SingleParticipantTestContext private[participant] (
applicationId = applicationId,
commandId = nextCommandId(),
submissionId = nextSubmissionId(),
actAs = Party.unsubst(actAs),
readAs = Party.unsubst(readAs),
commands = commands,
actAs = actAs.map(_.getValue),
readAs = readAs.map(_.getValue),
commands = commands.asScala.toSeq.map(c => ApiCommand.fromJavaProto(c.toProtoCommand)),
workflowId = workflowId,
)
)
)
override def submitRequest(party: Party, commands: Command*): SubmitRequest =
override def submitRequest(party: Party, commands: JList[Command] = JList.of()): SubmitRequest =
new SubmitRequest(
Some(
new Commands(
@ -661,8 +694,8 @@ final class SingleParticipantTestContext private[participant] (
applicationId = applicationId,
commandId = nextCommandId(),
submissionId = nextSubmissionId(),
party = party.unwrap,
commands = commands,
party = party.getValue,
commands = commands.asScala.toSeq.map(c => ApiCommand.fromJavaProto(c.toProtoCommand)),
workflowId = workflowId,
)
)
@ -671,7 +704,7 @@ final class SingleParticipantTestContext private[participant] (
override def submitAndWaitRequest(
actAs: List[Party],
readAs: List[Party],
commands: Command*
commands: JList[Command],
): SubmitAndWaitRequest =
new SubmitAndWaitRequest(
Some(
@ -680,15 +713,15 @@ final class SingleParticipantTestContext private[participant] (
applicationId = applicationId,
commandId = nextCommandId(),
submissionId = nextSubmissionId(),
actAs = Party.unsubst(actAs),
readAs = Party.unsubst(readAs),
commands = commands,
actAs = actAs.map(_.getValue),
readAs = readAs.map(_.getValue),
commands = commands.asScala.toSeq.map(c => ApiCommand.fromJavaProto(c.toProtoCommand)),
workflowId = workflowId,
)
)
)
override def submitAndWaitRequest(party: Party, commands: Command*): SubmitAndWaitRequest =
override def submitAndWaitRequest(party: Party, commands: JList[Command]): SubmitAndWaitRequest =
new SubmitAndWaitRequest(
Some(
new Commands(
@ -696,8 +729,8 @@ final class SingleParticipantTestContext private[participant] (
applicationId = applicationId,
commandId = nextCommandId(),
submissionId = nextSubmissionId(),
party = party.unwrap,
commands = commands,
party = party.getValue,
commands = commands.asScala.toSeq.map(c => ApiCommand.fromJavaProto(c.toProtoCommand)),
workflowId = workflowId,
)
)
@ -755,7 +788,7 @@ final class SingleParticipantTestContext private[participant] (
override def completionStreamRequest(from: LedgerOffset = referenceOffset)(
parties: Party*
): CompletionStreamRequest =
new CompletionStreamRequest(ledgerId, applicationId, parties.map(_.unwrap), Some(from))
new CompletionStreamRequest(ledgerId, applicationId, parties.map(_.getValue), Some(from))
override def completionEnd(request: CompletionEndRequest): Future[CompletionEndResponse] =
services.commandCompletion.completionEnd(request)
@ -887,8 +920,8 @@ final class SingleParticipantTestContext private[participant] (
override def pruneCantonSafe(
pruneUpTo: LedgerOffset,
party: Primitive.Party,
dummyCommand: Primitive.Party => Command,
party: Party,
dummyCommand: Party => JList[Command],
pruneAllDivulgedContracts: Boolean = false,
)(implicit ec: ExecutionContext): Future[Unit] =
FutureAssertions.succeedsEventually(
@ -922,5 +955,5 @@ final class SingleParticipantTestContext private[participant] (
} yield parties
private def reservePartyNames(n: Int): Future[Vector[Party]] =
Future.successful(Vector.fill(n)(Party(nextPartyHintId())))
Future.successful(Vector.fill(n)(new Party(nextPartyHintId())))
}

View File

@ -4,10 +4,9 @@
package com.daml.ledger.api.testtool.infrastructure.participant
import com.daml.error.ErrorCode
import java.time.Instant
import java.util.concurrent.TimeoutException
import com.daml.ledger.api.refinements.ApiTypes.TemplateId
import com.daml.ledger.api.testtool.infrastructure.Endpoint
import com.daml.ledger.api.testtool.infrastructure.participant.ParticipantTestContext.IncludeInterfaceView
import com.daml.ledger.api.testtool.infrastructure.time.{DelayMechanism, Durations}
@ -50,7 +49,6 @@ import com.daml.ledger.api.v1.command_service.{
SubmitAndWaitRequest,
}
import com.daml.ledger.api.v1.command_submission_service.SubmitRequest
import com.daml.ledger.api.v1.commands.Command
import com.daml.ledger.api.v1.completion.Completion
import com.daml.ledger.api.v1.event.CreatedEvent
import com.daml.ledger.api.v1.ledger_configuration_service.LedgerConfiguration
@ -70,14 +68,15 @@ import com.daml.ledger.api.v1.transaction_service.{
GetTransactionsRequest,
GetTransactionsResponse,
}
import com.daml.ledger.api.v1.value.Value
import com.daml.ledger.client.binding.{Primitive, Template}
import com.daml.ledger.javaapi.data.{Command, Identifier, Party, Template, Value, Unit => UnitData}
import com.daml.ledger.javaapi.data.codegen.{ContractCompanion, ContractId, Exercised, Update}
import com.daml.lf.data.Ref.HexString
import com.daml.timer.Delayed
import com.google.protobuf.ByteString
import io.grpc.health.v1.health.HealthCheckResponse
import io.grpc.stub.StreamObserver
import java.util.{List => JList}
import scala.concurrent.duration.DurationInt
import scala.concurrent.{ExecutionContext, Future}
@ -138,7 +137,7 @@ class TimeoutParticipantTestContext(timeoutScaleFactor: Double, delegate: Partic
s"Get package status $packageId",
delegate.getPackageStatus(packageId),
)
override def allocateParty(): Future[Primitive.Party] =
override def allocateParty(): Future[Party] =
withTimeout("Allocate party", delegate.allocateParty())
def allocateParty(req: AllocatePartyRequest): Future[AllocatePartyResponse] =
@ -162,7 +161,7 @@ class TimeoutParticipantTestContext(timeoutScaleFactor: Double, delegate: Partic
displayName: Option[String] = None,
localMetadata: Option[ObjectMeta] = None,
identityProviderId: Option[String] = None,
): Future[Primitive.Party] = withTimeout(
): Future[Party] = withTimeout(
s"Allocate party with hint $partyIdHint and display name $displayName",
delegate.allocateParty(partyIdHint, displayName, localMetadata, identityProviderId),
)
@ -172,15 +171,15 @@ class TimeoutParticipantTestContext(timeoutScaleFactor: Double, delegate: Partic
delegate.getParties(req),
)
override def allocateParties(n: Int): Future[Vector[Primitive.Party]] = withTimeout(
override def allocateParties(n: Int): Future[Vector[Party]] = withTimeout(
s"Allocate $n parties",
delegate.allocateParties(n),
)
override def getParties(parties: Seq[Primitive.Party]): Future[Seq[PartyDetails]] = withTimeout(
override def getParties(parties: Seq[Party]): Future[Seq[PartyDetails]] = withTimeout(
s"Get parties $parties",
delegate.getParties(parties),
)
override def listKnownParties(): Future[Set[Primitive.Party]] = withTimeout(
override def listKnownParties(): Future[Set[Party]] = withTimeout(
"List known parties",
delegate.listKnownParties(),
)
@ -191,7 +190,7 @@ class TimeoutParticipantTestContext(timeoutScaleFactor: Double, delegate: Partic
override def waitForParties(
otherParticipants: Iterable[ParticipantTestContext],
expectedParties: Set[Primitive.Party],
expectedParties: Set[Party],
): Future[Unit] = withTimeout(
s"Wait for parties $expectedParties on participants ${otherParticipants.map(_.ledgerEndpoint)}",
delegate.waitForParties(otherParticipants, expectedParties),
@ -203,9 +202,9 @@ class TimeoutParticipantTestContext(timeoutScaleFactor: Double, delegate: Partic
delegate.activeContracts(request),
)
override def activeContractsRequest(
parties: Seq[Primitive.Party],
templateIds: Seq[TemplateId],
interfaceFilters: Seq[(TemplateId, IncludeInterfaceView)] = Seq.empty,
parties: Seq[Party],
templateIds: Seq[Identifier],
interfaceFilters: Seq[(Identifier, IncludeInterfaceView)] = Seq.empty,
activeAtOffset: String = "",
useTemplateIdBasedLegacyFormat: Boolean = true,
): GetActiveContractsRequest =
@ -216,20 +215,20 @@ class TimeoutParticipantTestContext(timeoutScaleFactor: Double, delegate: Partic
activeAtOffset,
useTemplateIdBasedLegacyFormat,
)
override def activeContracts(parties: Primitive.Party*): Future[Vector[CreatedEvent]] =
override def activeContracts(parties: Party*): Future[Vector[CreatedEvent]] =
withTimeout(s"Active contracts for parties $parties", delegate.activeContracts(parties: _*))
override def activeContractsByTemplateId(
templateIds: Seq[TemplateId],
parties: Primitive.Party*
templateIds: Seq[Identifier],
parties: Party*
): Future[Vector[CreatedEvent]] = withTimeout(
s"Active contracts by template ids $templateIds for parties $parties",
delegate.activeContractsByTemplateId(templateIds, parties: _*),
)
def transactionFilter(
parties: Seq[Primitive.Party],
templateIds: Seq[TemplateId] = Seq.empty,
interfaceFilters: Seq[(TemplateId, IncludeInterfaceView)] = Seq.empty,
parties: Seq[Party],
templateIds: Seq[Identifier] = Seq.empty,
interfaceFilters: Seq[(Identifier, IncludeInterfaceView)] = Seq.empty,
useTemplateIdBasedLegacyFormat: Boolean = true,
): TransactionFilter =
delegate.transactionFilter(
@ -239,8 +238,8 @@ class TimeoutParticipantTestContext(timeoutScaleFactor: Double, delegate: Partic
useTemplateIdBasedLegacyFormat,
)
override def filters(
templateIds: Seq[TemplateId],
interfaceFilters: Seq[(TemplateId, IncludeInterfaceView)],
templateIds: Seq[Identifier],
interfaceFilters: Seq[(Identifier, IncludeInterfaceView)],
useTemplateIdBasedLegacyFormat: Boolean = true,
): Filters = delegate.filters(templateIds, interfaceFilters, useTemplateIdBasedLegacyFormat)
override def getTransactionsRequest(
@ -252,15 +251,15 @@ class TimeoutParticipantTestContext(timeoutScaleFactor: Double, delegate: Partic
responseObserver: StreamObserver[GetTransactionsResponse],
): Unit = delegate.transactionStream(request, responseObserver)
override def flatTransactionsByTemplateId(
templateId: TemplateId,
parties: Primitive.Party*
templateId: Identifier,
parties: Party*
): Future[Vector[Transaction]] = withTimeout(
s"Flat transaction by template id $templateId for parties $parties",
delegate.flatTransactionsByTemplateId(templateId, parties: _*),
)
override def flatTransactions(request: GetTransactionsRequest): Future[Vector[Transaction]] =
withTimeout(s"Flat transactions for request $request", delegate.flatTransactions(request))
override def flatTransactions(parties: Primitive.Party*): Future[Vector[Transaction]] =
override def flatTransactions(parties: Party*): Future[Vector[Transaction]] =
withTimeout(s"Flat transactions for parties $parties", delegate.flatTransactions(parties: _*))
override def flatTransactions(
take: Int,
@ -269,21 +268,21 @@ class TimeoutParticipantTestContext(timeoutScaleFactor: Double, delegate: Partic
s"$take flat transactions for request $request",
delegate.flatTransactions(take, request),
)
override def flatTransactions(take: Int, parties: Primitive.Party*): Future[Vector[Transaction]] =
override def flatTransactions(take: Int, parties: Party*): Future[Vector[Transaction]] =
withTimeout(
s"$take flat transactions for parties $parties",
delegate.flatTransactions(take, parties: _*),
)
override def transactionTreesByTemplateId(
templateId: TemplateId,
parties: Primitive.Party*
templateId: Identifier,
parties: Party*
): Future[Vector[TransactionTree]] = withTimeout(
s"Transaction trees by template id $templateId for parties $parties",
delegate.transactionTreesByTemplateId(templateId, parties: _*),
)
override def transactionTrees(request: GetTransactionsRequest): Future[Vector[TransactionTree]] =
withTimeout(s"Transaction trees for request $request", delegate.transactionTrees(request))
override def transactionTrees(parties: Primitive.Party*): Future[Vector[TransactionTree]] =
override def transactionTrees(parties: Party*): Future[Vector[TransactionTree]] =
withTimeout(s"Transaction trees for parties $parties", delegate.transactionTrees(parties: _*))
override def transactionTrees(
take: Int,
@ -294,14 +293,14 @@ class TimeoutParticipantTestContext(timeoutScaleFactor: Double, delegate: Partic
)
override def transactionTrees(
take: Int,
parties: Primitive.Party*
parties: Party*
): Future[Vector[TransactionTree]] = withTimeout(
s"$take transaction trees for parties $parties",
delegate.transactionTrees(take, parties: _*),
)
override def getTransactionByIdRequest(
transactionId: String,
parties: Seq[Primitive.Party],
parties: Seq[Party],
): GetTransactionByIdRequest =
delegate.getTransactionByIdRequest(transactionId, parties)
override def transactionTreeById(request: GetTransactionByIdRequest): Future[TransactionTree] =
@ -311,7 +310,7 @@ class TimeoutParticipantTestContext(timeoutScaleFactor: Double, delegate: Partic
)
override def transactionTreeById(
transactionId: String,
parties: Primitive.Party*
parties: Party*
): Future[TransactionTree] = withTimeout(
s"Get transaction tree by id for transaction id $transactionId and parties $parties",
delegate.transactionTreeById(transactionId, parties: _*),
@ -323,14 +322,14 @@ class TimeoutParticipantTestContext(timeoutScaleFactor: Double, delegate: Partic
)
override def flatTransactionById(
transactionId: String,
parties: Primitive.Party*
parties: Party*
): Future[Transaction] = withTimeout(
s"Flat transaction by id for transaction id $transactionId and parties $parties",
delegate.flatTransactionById(transactionId, parties: _*),
)
override def getTransactionByEventIdRequest(
eventId: String,
parties: Seq[Primitive.Party],
parties: Seq[Party],
): GetTransactionByEventIdRequest =
delegate.getTransactionByEventIdRequest(eventId, parties)
override def transactionTreeByEventId(
@ -341,7 +340,7 @@ class TimeoutParticipantTestContext(timeoutScaleFactor: Double, delegate: Partic
)
override def transactionTreeByEventId(
eventId: String,
parties: Primitive.Party*
parties: Party*
): Future[TransactionTree] = withTimeout(
s"Transaction tree by event id for event id $eventId and parties $parties",
delegate.transactionTreeByEventId(eventId, parties: _*),
@ -354,7 +353,7 @@ class TimeoutParticipantTestContext(timeoutScaleFactor: Double, delegate: Partic
)
override def flatTransactionByEventId(
eventId: String,
parties: Primitive.Party*
parties: Party*
): Future[Transaction] = withTimeout(
s"Flat transaction by event id for event id $eventId and parties $parties",
delegate.flatTransactionByEventId(eventId, parties: _*),
@ -374,56 +373,68 @@ class TimeoutParticipantTestContext(timeoutScaleFactor: Double, delegate: Partic
delegate.getEventsByContractKey(request),
)
override def create[T](
party: Primitive.Party,
template: Template[T],
): Future[Primitive.ContractId[T]] =
override def create[
TCid <: ContractId[T],
T <: Template,
](
party: Party,
template: T,
)(implicit companion: ContractCompanion[?, TCid, T]): Future[TCid] =
withTimeout(s"Create template for party $party", delegate.create(party, template))
override def create[T](
actAs: List[Primitive.Party],
readAs: List[Primitive.Party],
template: Template[T],
): Future[Primitive.ContractId[T]] = withTimeout(
override def create[TCid <: ContractId[T], T <: Template](
actAs: List[Party],
readAs: List[Party],
template: T,
)(implicit companion: ContractCompanion[?, TCid, T]): Future[TCid] = withTimeout(
s"Create template for actAs $actAs and readAs $readAs",
delegate.create(actAs, readAs, template),
)
override def createAndGetTransactionId[T](
party: Primitive.Party,
template: Template[T],
): Future[(String, Primitive.ContractId[T])] = withTimeout(
override def createAndGetTransactionId[TCid <: ContractId[
T
], T <: Template](
party: Party,
template: T,
)(implicit companion: ContractCompanion[?, TCid, T]): Future[(String, TCid)] = withTimeout(
s"Create and get transaction id for party $party",
delegate.createAndGetTransactionId(party, template),
)
override def exercise[T](
party: Primitive.Party,
exercise: Primitive.Update[T],
party: Party,
exercise: Update[T],
): Future[TransactionTree] =
withTimeout(s"Exercise for party $party", delegate.exercise(party, exercise))
override def exercise[T](
actAs: List[Primitive.Party],
readAs: List[Primitive.Party],
exercise: Primitive.Update[T],
actAs: List[Party],
readAs: List[Party],
exercise: Update[T],
): Future[TransactionTree] = withTimeout(
s"Exercise for actAs $actAs and readAs $readAs",
delegate.exercise(actAs, readAs, exercise),
)
override def exerciseForFlatTransaction[T](
party: Primitive.Party,
exercise: Primitive.Update[T],
party: Party,
exercise: Update[T],
): Future[Transaction] = withTimeout(
s"Exercise for flat transaction for party $party",
delegate.exerciseForFlatTransaction(party, exercise),
)
override def exerciseAndGetContract[T](
party: Primitive.Party,
exercise: Primitive.Update[Any],
): Future[Primitive.ContractId[T]] = withTimeout(
override def exerciseAndGetContract[TCid <: ContractId[T], T](
party: Party,
exercise: Update[Exercised[TCid]],
)(implicit companion: ContractCompanion[?, TCid, T]): Future[TCid] = withTimeout(
s"Exercise and get contract for party $party",
delegate.exerciseAndGetContract(party, exercise),
delegate.exerciseAndGetContract[TCid, T](party, exercise),
)
override def exerciseByKey[T](
party: Primitive.Party,
template: Primitive.TemplateId[T],
override def exerciseAndGetContractNoDisclose[TCid <: ContractId[?]](
party: Party,
exercise: Update[Exercised[UnitData]],
)(implicit companion: ContractCompanion[?, TCid, ?]): Future[TCid] = withTimeout(
s"Exercise and get non disclosed contract for party $party",
delegate.exerciseAndGetContractNoDisclose[TCid](party, exercise),
)
override def exerciseByKey(
party: Party,
template: Identifier,
key: Value,
choice: String,
argument: Value,
@ -432,21 +443,21 @@ class TimeoutParticipantTestContext(timeoutScaleFactor: Double, delegate: Partic
delegate.exerciseByKey(party, template, key, choice, argument),
)
override def submitRequest(
actAs: List[Primitive.Party],
readAs: List[Primitive.Party],
commands: Command*
): SubmitRequest = delegate.submitRequest(actAs, readAs, commands: _*)
override def submitRequest(party: Primitive.Party, commands: Command*): SubmitRequest =
delegate.submitRequest(party, commands: _*)
actAs: List[Party],
readAs: List[Party],
commands: JList[Command],
): SubmitRequest = delegate.submitRequest(actAs, readAs, commands)
override def submitRequest(party: Party, commands: JList[Command] = JList.of()): SubmitRequest =
delegate.submitRequest(party, commands)
override def submitAndWaitRequest(
actAs: List[Primitive.Party],
readAs: List[Primitive.Party],
commands: Command*
): SubmitAndWaitRequest = delegate.submitAndWaitRequest(actAs, readAs, commands: _*)
actAs: List[Party],
readAs: List[Party],
commands: JList[Command],
): SubmitAndWaitRequest = delegate.submitAndWaitRequest(actAs, readAs, commands)
override def submitAndWaitRequest(
party: Primitive.Party,
commands: Command*
): SubmitAndWaitRequest = delegate.submitAndWaitRequest(party, commands: _*)
party: Party,
commands: JList[Command],
): SubmitAndWaitRequest = delegate.submitAndWaitRequest(party, commands)
override def submit(request: SubmitRequest): Future[Unit] =
withTimeout(s"Submit for request $request", delegate.submit(request))
override def submitAndWait(request: SubmitAndWaitRequest): Future[Unit] = withTimeout(
@ -477,7 +488,7 @@ class TimeoutParticipantTestContext(timeoutScaleFactor: Double, delegate: Partic
): Future[T] = // timeout enforced by submitAndWaitGeneric
delegate.submitRequestAndTolerateGrpcError(errorToTolerate, submitAndWaitGeneric)
override def completionStreamRequest(from: LedgerOffset)(
parties: Primitive.Party*
parties: Party*
): CompletionStreamRequest = delegate.completionStreamRequest(from)(parties: _*)
override def completionEnd(request: CompletionEndRequest): Future[CompletionEndResponse] =
withTimeout(
@ -493,13 +504,13 @@ class TimeoutParticipantTestContext(timeoutScaleFactor: Double, delegate: Partic
s"First completions for request $request",
delegate.firstCompletions(request),
)
override def firstCompletions(parties: Primitive.Party*): Future[Vector[Completion]] =
override def firstCompletions(parties: Party*): Future[Vector[Completion]] =
withTimeout(
s"First completions for parties $parties",
delegate.firstCompletions(parties: _*),
)
override def findCompletionAtOffset(offset: HexString, p: Completion => Boolean)(
parties: Primitive.Party*
parties: Party*
): Future[Option[ParticipantTestContext.CompletionResponse]] = withTimeout(
s"Find completion at offset $offset for parties $parties",
delegate.findCompletionAtOffset(offset, p)(parties: _*),
@ -510,14 +521,14 @@ class TimeoutParticipantTestContext(timeoutScaleFactor: Double, delegate: Partic
s"Find completion for request $request",
delegate.findCompletion(request)(p),
)
override def findCompletion(parties: Primitive.Party*)(
override def findCompletion(parties: Party*)(
p: Completion => Boolean
): Future[Option[ParticipantTestContext.CompletionResponse]] =
withTimeout(s"Find completion for parties $parties", delegate.findCompletion(parties: _*)(p))
override def checkpoints(n: Int, request: CompletionStreamRequest): Future[Vector[Checkpoint]] =
withTimeout(s"$n checkpoints for request $request", delegate.checkpoints(n, request))
override def checkpoints(n: Int, from: LedgerOffset)(
parties: Primitive.Party*
parties: Party*
): Future[Vector[Checkpoint]] = withTimeout(
s"$n checkpoints from offset $from for parties $parties",
delegate.checkpoints(n, from)(parties: _*),
@ -526,7 +537,7 @@ class TimeoutParticipantTestContext(timeoutScaleFactor: Double, delegate: Partic
s"First checkpoint for request $request",
delegate.firstCheckpoint(request),
)
override def firstCheckpoint(parties: Primitive.Party*): Future[Checkpoint] = withTimeout(
override def firstCheckpoint(parties: Party*): Future[Checkpoint] = withTimeout(
s"First checkpoint for parties $parties",
delegate.firstCheckpoint(parties: _*),
)
@ -534,7 +545,7 @@ class TimeoutParticipantTestContext(timeoutScaleFactor: Double, delegate: Partic
s"Next checkpoint for request $request",
delegate.nextCheckpoint(request),
)
override def nextCheckpoint(from: LedgerOffset, parties: Primitive.Party*): Future[Checkpoint] =
override def nextCheckpoint(from: LedgerOffset, parties: Party*): Future[Checkpoint] =
withTimeout(
s"Next checkpoint from offset $from for parties $parties",
delegate.nextCheckpoint(from, parties: _*),
@ -586,8 +597,8 @@ class TimeoutParticipantTestContext(timeoutScaleFactor: Double, delegate: Partic
override def pruneCantonSafe(
pruneUpTo: LedgerOffset,
party: Primitive.Party,
dummyCommand: Primitive.Party => Command,
party: Party,
dummyCommand: Party => JList[Command],
pruneAllDivulgedContracts: Boolean = false,
)(implicit ec: ExecutionContext): Future[Unit] =
delegate.pruneCantonSafe(pruneUpTo, party, dummyCommand, pruneAllDivulgedContracts)

View File

@ -12,15 +12,16 @@ def _has_model_tests(lf_version):
def deps(lf_version):
carbon_tests = [
"//test-common:carbonv1-tests-%s.scala" % lf_version,
"//test-common:carbonv2-tests-%s.scala" % lf_version,
"//test-common:carbonv3-tests-%s.scala" % lf_version,
"//test-common:carbonv1-tests-%s.java-codegen" % lf_version,
"//test-common:carbonv2-tests-%s.java-codegen" % lf_version,
"//test-common:carbonv3-tests-%s.java-codegen" % lf_version,
]
additional_tests = carbon_tests if _has_model_tests(lf_version) else []
return [
"//daml-lf/data",
"//daml-lf/transaction",
"//language-support/scala/bindings",
"//ledger-api/grpc-definitions:ledger_api_proto_scala",
"//language-support/java/bindings:bindings-java",
"//ledger/error",
"//ledger/ledger-api-errors",
"//ledger/ledger-api-common",
@ -28,9 +29,9 @@ def deps(lf_version):
"//libs-scala/ledger-resources",
"//libs-scala/test-evidence/tag:test-evidence-tag",
"//test-common:dar-files-%s-lib" % lf_version,
"//test-common:model-tests-%s.scala" % lf_version,
"//test-common:package_management-tests-%s.scala" % lf_version,
"//test-common:semantic-tests-%s.scala" % lf_version,
"//test-common:model-tests-%s.java-codegen" % lf_version,
"//test-common:package_management-tests-%s.java-codegen" % lf_version,
"//test-common:semantic-tests-%s.java-codegen" % lf_version,
"//libs-scala/contextualized-logging",
"//libs-scala/grpc-utils",
"//libs-scala/resources",

View File

@ -10,8 +10,9 @@ import com.daml.ledger.api.testtool.infrastructure.participant.ParticipantTestCo
import com.daml.ledger.api.testtool.infrastructure.RaceConditionTests._
import com.daml.ledger.api.v1.transaction.{TransactionTree, TreeEvent}
import com.daml.ledger.api.v1.value.RecordField
import com.daml.ledger.client.binding.Primitive
import com.daml.ledger.test.semantic.ExceptionRaceTests._
import com.daml.ledger.javaapi.data.Party
import com.daml.ledger.javaapi.data.codegen.ContractCompanion
import com.daml.ledger.test.java.semantic.exceptionracetests._
import scala.annotation.nowarn
import scala.concurrent.{ExecutionContext, Future}
@ -19,16 +20,17 @@ import scala.concurrent.{ExecutionContext, Future}
final class ExceptionRaceConditionIT extends LedgerTestSuite {
import ExceptionRaceConditionIT.ExceptionRaceTests
import ExceptionRaceConditionIT.CompanionImplicits._
raceConditionTest(
"RWRollbackCreateVsNonTransientCreate",
"Cannot create a contract in a rollback and a non-transient contract with the same key",
) { implicit ec => ledger => alice =>
for {
wrapper <- ledger.create(alice, CreateWrapper(alice))
wrapper <- ledger.create(alice, new CreateWrapper(alice))
_ <- executeRepeatedlyWithRandomDelay(
numberOfAttempts = 20,
once = ledger.create(alice, ContractWithKey(alice)).map(_ => ()),
once = ledger.create(alice, new ContractWithKey(alice)).map(_ => ()),
repeated =
ledger.exercise(alice, wrapper.exerciseCreateWrapper_CreateRollback()).map(_ => ()),
)
@ -52,8 +54,8 @@ final class ExceptionRaceConditionIT extends LedgerTestSuite {
"Cannot exercise a non-consuming choice in a rollback after a contract archival",
) { implicit ec => ledger => alice =>
for {
wrapper <- ledger.create(alice, ExerciseWrapper(alice))
contract <- ledger.create(alice, ContractWithKey(alice))
wrapper: ExerciseWrapper.ContractId <- ledger.create(alice, new ExerciseWrapper(alice))
contract: ContractWithKey.ContractId <- ledger.create(alice, new ContractWithKey(alice))
_ <- executeRepeatedlyWithRandomDelay(
numberOfAttempts = 10,
once = ledger.exercise(alice, contract.exerciseContractWithKey_Archive()),
@ -77,8 +79,8 @@ final class ExceptionRaceConditionIT extends LedgerTestSuite {
"Cannot exercise a consuming choice in a rollback after a contract archival",
) { implicit ec => ledger => alice =>
for {
wrapper <- ledger.create(alice, ExerciseWrapper(alice))
contract <- ledger.create(alice, ContractWithKey(alice))
wrapper: ExerciseWrapper.ContractId <- ledger.create(alice, new ExerciseWrapper(alice))
contract: ContractWithKey.ContractId <- ledger.create(alice, new ContractWithKey(alice))
_ <- executeRepeatedlyWithRandomDelay(
numberOfAttempts = 10,
once = ledger.exercise(alice, contract.exerciseContractWithKey_Archive()),
@ -102,8 +104,11 @@ final class ExceptionRaceConditionIT extends LedgerTestSuite {
"Cannot fetch in a rollback after a contract archival",
) { implicit ec => ledger => alice =>
for {
contract <- ledger.create(alice, ContractWithKey(alice))
fetchConract <- ledger.create(alice, FetchWrapper(alice, contract))
contract: ContractWithKey.ContractId <- ledger.create(alice, new ContractWithKey(alice))
fetchConract: FetchWrapper.ContractId <- ledger.create(
alice,
new FetchWrapper(alice, contract),
)
_ <- executeRepeatedlyWithRandomDelay(
numberOfAttempts = 10,
once = ledger.exercise(alice, contract.exerciseContractWithKey_Archive()),
@ -124,8 +129,8 @@ final class ExceptionRaceConditionIT extends LedgerTestSuite {
"Cannot successfully lookup by key in a rollback after a contract archival",
) { implicit ec => ledger => alice =>
for {
contract <- ledger.create(alice, ContractWithKey(alice))
looker <- ledger.create(alice, LookupWrapper(alice))
contract: ContractWithKey.ContractId <- ledger.create(alice, new ContractWithKey(alice))
looker: LookupWrapper.ContractId <- ledger.create(alice, new LookupWrapper(alice))
_ <- executeRepeatedlyWithRandomDelay(
numberOfAttempts = 20,
once = ledger.exercise(alice, contract.exerciseContractWithKey_Archive()),
@ -146,10 +151,10 @@ final class ExceptionRaceConditionIT extends LedgerTestSuite {
"Lookup by key in a rollback cannot fail after a contract creation",
) { implicit ec => ledger => alice =>
for {
looker <- ledger.create(alice, LookupWrapper(alice))
looker: LookupWrapper.ContractId <- ledger.create(alice, new LookupWrapper(alice))
_ <- executeRepeatedlyWithRandomDelay(
numberOfAttempts = 5,
once = ledger.create(alice, ContractWithKey(alice)),
once = ledger.create(alice, new ContractWithKey(alice)),
repeated = ledger.exercise(alice, looker.exerciseLookupWrapper_Lookup()),
): @nowarn("cat=lint-infer-any")
transactions <- transactions(ledger, alice)
@ -170,7 +175,7 @@ final class ExceptionRaceConditionIT extends LedgerTestSuite {
description: String,
repeated: Int = DefaultRepetitionsNumber,
runConcurrently: Boolean = false,
)(testCase: ExecutionContext => ParticipantTestContext => Primitive.Party => Future[Unit]): Unit =
)(testCase: ExecutionContext => ParticipantTestContext => Party => Future[Unit]): Unit =
test(
shortIdentifier = shortIdentifier,
description = description,
@ -245,4 +250,34 @@ object ExceptionRaceConditionIT {
val ChoiceConsumingRollback = "ExerciseWrapper_ExerciseConsumingRollback"
}
}
private object CompanionImplicits {
implicit val createWrapperCompanion: ContractCompanion.WithoutKey[
CreateWrapper.Contract,
CreateWrapper.ContractId,
CreateWrapper,
] = CreateWrapper.COMPANION
implicit val contractWithKeyCompanion: ContractCompanion.WithKey[
ContractWithKey.Contract,
ContractWithKey.ContractId,
ContractWithKey,
String,
] = ContractWithKey.COMPANION
implicit val lookupWrapperCompanion: ContractCompanion.WithoutKey[
LookupWrapper.Contract,
LookupWrapper.ContractId,
LookupWrapper,
] = LookupWrapper.COMPANION
implicit val fetchWrapperCompanion: ContractCompanion.WithoutKey[
FetchWrapper.Contract,
FetchWrapper.ContractId,
FetchWrapper,
] = FetchWrapper.COMPANION
implicit val exerciseWrapperCompanion: ContractCompanion.WithoutKey[
ExerciseWrapper.Contract,
ExerciseWrapper.ContractId,
ExerciseWrapper,
] = ExerciseWrapper.COMPANION
}
}

View File

@ -9,17 +9,24 @@ import com.daml.ledger.api.testtool.infrastructure.Assertions._
import com.daml.ledger.api.testtool.infrastructure.LedgerTestSuite
import com.daml.ledger.api.testtool.infrastructure.Synchronize.synchronize
import com.daml.ledger.api.testtool.infrastructure.TransactionHelpers._
import com.daml.ledger.test.semantic.Exceptions._
import com.daml.ledger.javaapi.data.codegen.ContractCompanion
import com.daml.ledger.test.java.semantic.da.types
import com.daml.ledger.test.java.semantic.exceptions._
import java.lang
import java.util.regex.Pattern
import scala.jdk.CollectionConverters._
final class ExceptionsIT extends LedgerTestSuite {
import ExceptionsIT.CompanionImplicits._
test(
"ExUncaught",
"Uncaught exception returns INVALID_ARGUMENT",
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
for {
t <- ledger.create(party, ExceptionTester(party))
t <- ledger.create(party, new ExceptionTester(party))
failure <- ledger.exercise(party, t.exerciseThrowUncaught()).mustFail("Unhandled exception")
} yield {
assertGrpcErrorRegex(
@ -37,7 +44,7 @@ final class ExceptionsIT extends LedgerTestSuite {
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
for {
t <- ledger.create(party, ExceptionTester(party))
t <- ledger.create(party, new ExceptionTester(party))
tree <- ledger.exercise(party, t.exerciseThrowCaught())
} yield {
assertLength(s"1 successful exercise", 1, exercisedEvents(tree))
@ -51,7 +58,7 @@ final class ExceptionsIT extends LedgerTestSuite {
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
for {
t <- ledger.create(party, ExceptionTester(party))
t <- ledger.create(party, new ExceptionTester(party))
tree <- ledger.exercise(party, t.exerciseNestedCatch())
} yield {
assertLength(s"1 successful exercise", 1, exercisedEvents(tree))
@ -65,8 +72,8 @@ final class ExceptionsIT extends LedgerTestSuite {
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
for {
t <- ledger.create(party, ExceptionTester(party))
tFetch <- ledger.create(party, ExceptionTester(party))
t <- ledger.create(party, new ExceptionTester(party))
tFetch <- ledger.create(party, new ExceptionTester(party))
_ <- ledger.exercise(party, t.exerciseRollbackFetch(tFetch))
_ <- ledger.exercise(party, tFetch.exerciseArchive())
failure <- ledger
@ -88,8 +95,8 @@ final class ExceptionsIT extends LedgerTestSuite {
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
for {
t <- ledger.create(party, ExceptionTester(party))
tExercise <- ledger.create(party, ExceptionTester(party))
t <- ledger.create(party, new ExceptionTester(party))
tExercise <- ledger.create(party, new ExceptionTester(party))
_ <- ledger.exercise(party, t.exerciseRollbackConsuming(tExercise))
_ <- ledger.exercise(party, tExercise.exerciseArchive())
failure <- ledger
@ -111,8 +118,8 @@ final class ExceptionsIT extends LedgerTestSuite {
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
for {
t <- ledger.create(party, ExceptionTester(party))
tExercise <- ledger.create(party, ExceptionTester(party))
t <- ledger.create(party, new ExceptionTester(party))
tExercise <- ledger.create(party, new ExceptionTester(party))
_ <- ledger.exercise(party, t.exerciseRollbackNonConsuming(tExercise))
_ <- ledger.exercise(party, tExercise.exerciseArchive())
failure <- ledger
@ -134,8 +141,8 @@ final class ExceptionsIT extends LedgerTestSuite {
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
for {
t <- ledger.create(party, ExceptionTester(party))
withKey <- ledger.create(party, WithSimpleKey(party))
t <- ledger.create(party, new ExceptionTester(party))
withKey <- ledger.create(party, new WithSimpleKey(party))
_ <- ledger.exercise(party, t.exerciseRolledbackArchiveConsuming(withKey))
} yield ()
})
@ -146,8 +153,8 @@ final class ExceptionsIT extends LedgerTestSuite {
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
for {
t <- ledger.create(party, ExceptionTester(party))
withKey <- ledger.create(party, WithSimpleKey(party))
t <- ledger.create(party, new ExceptionTester(party))
withKey <- ledger.create(party, new WithSimpleKey(party))
_ <- ledger.exercise(party, t.exerciseRolledbackArchiveNonConsuming(withKey))
} yield ()
})
@ -158,7 +165,7 @@ final class ExceptionsIT extends LedgerTestSuite {
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
for {
t <- ledger.create(party, ExceptionTester(party))
t <- ledger.create(party, new ExceptionTester(party))
_ <- ledger.exercise(party, t.exerciseRolledbackDuplicateKey())
} yield ()
})
@ -169,9 +176,9 @@ final class ExceptionsIT extends LedgerTestSuite {
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
for {
t <- ledger.create(party, ExceptionTester(party))
t <- ledger.create(party, new ExceptionTester(party))
_ <- ledger.exercise(party, t.exerciseDuplicateKey())
_ <- ledger.create(party, WithSimpleKey(party))
_ <- ledger.create(party, new WithSimpleKey(party))
failure <- ledger.exercise(party, t.exerciseDuplicateKey()).mustFail("duplicate key")
} yield {
assertGrpcError(
@ -189,8 +196,8 @@ final class ExceptionsIT extends LedgerTestSuite {
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
for {
t <- ledger.create(party, ExceptionTester(party))
withKey <- ledger.create(party, WithSimpleKey(party))
t <- ledger.create(party, new ExceptionTester(party))
withKey <- ledger.create(party, new WithSimpleKey(party))
failure <- ledger.exercise(party, t.exerciseDuplicateKey()).mustFail("duplicate key")
_ = assertGrpcError(
failure,
@ -209,8 +216,8 @@ final class ExceptionsIT extends LedgerTestSuite {
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
for {
t <- ledger.create(party, ExceptionTester(party))
withKey <- ledger.create(party, WithSimpleKey(party))
t <- ledger.create(party, new ExceptionTester(party))
withKey <- ledger.create(party, new WithSimpleKey(party))
_ <- ledger.exercise(party, t.exerciseFetchKey())
_ <- ledger.exercise(party, withKey.exerciseArchive())
failure <- ledger.exercise(party, t.exerciseFetchKey()).mustFail("couldn't find key")
@ -231,7 +238,7 @@ final class ExceptionsIT extends LedgerTestSuite {
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
for {
t <- ledger.create(party, ExceptionTester(party))
t <- ledger.create(party, new ExceptionTester(party))
failure <- ledger.exercise(party, t.exerciseFetchKey()).mustFail("contract not found")
_ = assertGrpcError(
failure,
@ -239,7 +246,7 @@ final class ExceptionsIT extends LedgerTestSuite {
Some("couldn't find key"),
checkDefiniteAnswerMetadata = true,
)
_ <- ledger.create(party, WithSimpleKey(party))
_ <- ledger.create(party, new WithSimpleKey(party))
_ <- ledger.exercise(party, t.exerciseFetchKey())
} yield ()
})
@ -250,7 +257,7 @@ final class ExceptionsIT extends LedgerTestSuite {
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
for {
t <- ledger.create(party, ExceptionTester(party))
t <- ledger.create(party, new ExceptionTester(party))
tree <- ledger.exercise(party, t.exerciseRollbackCreate())
} yield {
// Create node should not be included
@ -269,9 +276,9 @@ final class ExceptionsIT extends LedgerTestSuite {
)(implicit ec => {
case Participants(Participant(aLedger, aParty), Participant(bLedger, bParty)) =>
for {
divulger <- aLedger.create(aParty, Divulger(aParty, bParty))
fetcher <- bLedger.create(bParty, Fetcher(bParty, aParty))
t <- bLedger.create(bParty, WithSimpleKey(bParty))
divulger <- aLedger.create(aParty, new Divulger(aParty, bParty))
fetcher <- bLedger.create(bParty, new Fetcher(bParty, aParty))
t <- bLedger.create(bParty, new WithSimpleKey(bParty))
_ <- synchronize(aLedger, bLedger)
fetchFailure <- aLedger
.exercise(aParty, fetcher.exerciseFetch(t))
@ -296,9 +303,9 @@ final class ExceptionsIT extends LedgerTestSuite {
)(implicit ec => {
case Participants(Participant(aLedger, aParty), Participant(bLedger, bParty)) =>
for {
fetcher <- aLedger.create(aParty, Fetcher(aParty, bParty))
withKey0 <- aLedger.create(aParty, WithKey(aParty, 0, List.empty))
withKey1 <- aLedger.create(aParty, WithKey(aParty, 1, List.empty))
fetcher <- aLedger.create(aParty, new Fetcher(aParty, bParty))
withKey0 <- aLedger.create(aParty, new WithKey(aParty, 0, List.empty.asJava))
withKey1 <- aLedger.create(aParty, new WithKey(aParty, 1, List.empty.asJava))
_ <- synchronize(aLedger, bLedger)
fetchFailure <- bLedger
.exercise(bParty, fetcher.exerciseFetch_(withKey0))
@ -318,7 +325,7 @@ final class ExceptionsIT extends LedgerTestSuite {
Some("Contract could not be found"),
checkDefiniteAnswerMetadata = true,
)
tester <- aLedger.create(aParty, ExceptionTester(aParty))
tester <- aLedger.create(aParty, new ExceptionTester(aParty))
_ <- aLedger.exercise(aParty, tester.exerciseProjectionDivulgence(bParty, withKey0))
_ <- synchronize(aLedger, bLedger)
_ <- bLedger
@ -343,13 +350,16 @@ final class ExceptionsIT extends LedgerTestSuite {
Participant(cLedger, cParty),
) =>
for {
abInformer <- aLedger.create(aParty, Informer(aParty, List(bParty)))
acInformer <- aLedger.create(aParty, Informer(aParty, List(cParty)))
abcInformer <- aLedger.create(aParty, Informer(aParty, List(bParty, cParty)))
keyDelegate <- bLedger.create(bParty, WithKeyDelegate(aParty, bParty))
abInformer <- aLedger.create(aParty, new Informer(aParty, List(bParty.getValue).asJava))
acInformer <- aLedger.create(aParty, new Informer(aParty, List(cParty.getValue).asJava))
abcInformer <- aLedger.create(
aParty,
new Informer(aParty, List(bParty, cParty).map(_.getValue).asJava),
)
keyDelegate <- bLedger.create(bParty, new WithKeyDelegate(aParty, bParty))
_ <- synchronize(aLedger, bLedger)
_ <- synchronize(aLedger, cLedger)
tester <- aLedger.create(aParty, ExceptionTester(aParty))
tester <- aLedger.create(aParty, new ExceptionTester(aParty))
_ <- aLedger.exercise(
aParty,
tester.exerciseProjectionNormalization(
@ -378,11 +388,11 @@ final class ExceptionsIT extends LedgerTestSuite {
Participant(cLedger, cParty),
) =>
for {
keyDelegate <- bLedger.create(bParty, WithKeyDelegate(aParty, bParty))
nestingHelper <- cLedger.create(cParty, RollbackNestingHelper(aParty, bParty, cParty))
keyDelegate <- bLedger.create(bParty, new WithKeyDelegate(aParty, bParty))
nestingHelper <- cLedger.create(cParty, new RollbackNestingHelper(aParty, bParty, cParty))
_ <- synchronize(aLedger, bLedger)
_ <- synchronize(aLedger, cLedger)
tester <- aLedger.create(aParty, ExceptionTester(aParty))
tester <- aLedger.create(aParty, new ExceptionTester(aParty))
_ <- aLedger.exercise(
aParty,
tester.exerciseProjectionNesting(bParty, keyDelegate, nestingHelper),
@ -399,8 +409,8 @@ final class ExceptionsIT extends LedgerTestSuite {
Participant(ledger, party)
) =>
for {
t <- ledger.create(party, ExceptionTester(party))
withKey <- ledger.create(party, WithSimpleKey(party))
t <- ledger.create(party, new ExceptionTester(party))
withKey <- ledger.create(party, new WithSimpleKey(party))
_ <- ledger.exercise(party, t.exerciseRollbackGlobalArchivedLookup(withKey))
} yield ()
})
@ -414,8 +424,8 @@ final class ExceptionsIT extends LedgerTestSuite {
Participant(ledger, party)
) =>
for {
t <- ledger.create(party, ExceptionTester(party))
withKey <- ledger.create(party, WithSimpleKey(party))
t <- ledger.create(party, new ExceptionTester(party))
withKey <- ledger.create(party, new WithSimpleKey(party))
_ <- ledger.exercise(party, t.exerciseRollbackGlobalArchivedCreate(withKey))
} yield ()
})
@ -426,7 +436,7 @@ final class ExceptionsIT extends LedgerTestSuite {
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
for {
t <- ledger.create(party, ExceptionTester(party))
t <- ledger.create(party, new ExceptionTester(party))
failure <- ledger
.exercise(party, t.exerciseRollbackCreateBecomesInactive())
.mustFail("contract is inactive")
@ -446,10 +456,51 @@ final class ExceptionsIT extends LedgerTestSuite {
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
for {
helper <- ledger.create(party, ExceptionTester(party))
withKey <- ledger.create(party, WithSimpleKey(party))
helper <- ledger.create(party, new ExceptionTester(party))
withKey <- ledger.create(party, new WithSimpleKey(party))
_ <- ledger.exercise(party, helper.exerciseRollbackExerciseCreateLookup(withKey))
} yield ()
})
}
object ExceptionsIT {
private object CompanionImplicits {
implicit val exceptionTesterCompanion: ContractCompanion.WithoutKey[
ExceptionTester.Contract,
ExceptionTester.ContractId,
ExceptionTester,
] = ExceptionTester.COMPANION
implicit val withSimpleKeyCompanion: ContractCompanion.WithKey[
WithSimpleKey.Contract,
WithSimpleKey.ContractId,
WithSimpleKey,
String,
] = WithSimpleKey.COMPANION
implicit val withKeyCompanion: ContractCompanion.WithKey[
WithKey.Contract,
WithKey.ContractId,
WithKey,
types.Tuple2[String, lang.Long],
] = WithKey.COMPANION
implicit val informerCompanion
: ContractCompanion.WithoutKey[Informer.Contract, Informer.ContractId, Informer] =
Informer.COMPANION
implicit val withKeyDelegateCompanion: ContractCompanion.WithoutKey[
WithKeyDelegate.Contract,
WithKeyDelegate.ContractId,
WithKeyDelegate,
] = WithKeyDelegate.COMPANION
implicit val divulgerCompanion
: ContractCompanion.WithoutKey[Divulger.Contract, Divulger.ContractId, Divulger] =
Divulger.COMPANION
implicit val fetcherCompanion
: ContractCompanion.WithoutKey[Fetcher.Contract, Fetcher.ContractId, Fetcher] =
Fetcher.COMPANION
implicit val rollbackNestingHelperCompanion: ContractCompanion.WithoutKey[
RollbackNestingHelper.Contract,
RollbackNestingHelper.ContractId,
RollbackNestingHelper,
] = RollbackNestingHelper.COMPANION
}
}

View File

@ -5,8 +5,9 @@ package com.daml.ledger.api.testtool.suites.v1_14
import com.daml.ledger.api.testtool.infrastructure.Allocation._
import com.daml.ledger.api.testtool.infrastructure.LedgerTestSuite
import com.daml.ledger.client.binding.Primitive.Party
import com.daml.ledger.test.semantic.Limits.{WithList, WithMap}
import com.daml.ledger.test.java.semantic.limits.{WithList, WithMap}
import scala.jdk.CollectionConverters._
final class LimitsIT extends LedgerTestSuite {
@ -15,9 +16,11 @@ final class LimitsIT extends LedgerTestSuite {
"Create a contract with a field containing large map",
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, alice)) =>
val elements = (1 to 10000).map(e => (f"element_$e%08d", alice)).toMap
val elements = (1 to 10000).map(e => (f"element_$e%08d", alice.getValue)).toMap.asJava
for {
contract <- ledger.create(alice, WithMap(alice, elements))
contract: WithMap.ContractId <- ledger.create(alice, new WithMap(alice, elements))(
WithMap.COMPANION
)
_ <- ledger.exercise(alice, contract.exerciseWithMap_Noop())
} yield {
()
@ -29,9 +32,12 @@ final class LimitsIT extends LedgerTestSuite {
"Exercise a choice with a large map",
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, alice)) =>
val elements = (1 to 10000).map(e => (f"element_$e%08d", alice)).toMap
val elements = (1 to 10000).map(e => (f"element_$e%08d", alice.getValue)).toMap.asJava
for {
contract <- ledger.create(alice, WithMap(alice, Map.empty[String, Party]))
contract: WithMap.ContractId <- ledger.create(
alice,
new WithMap(alice, Map.empty[String, String].asJava),
)(WithMap.COMPANION)
_ <- ledger.exercise(alice, contract.exerciseWithMap_Expand(elements))
} yield {
()
@ -43,9 +49,11 @@ final class LimitsIT extends LedgerTestSuite {
"Create a contract with a field containing large list",
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, alice)) =>
val elements = (1 to 10000).map(e => f"element_$e%08d")
val elements = (1 to 10000).map(e => f"element_$e%08d").asJava
for {
contract <- ledger.create(alice, WithList(alice, elements))
contract: WithList.ContractId <- ledger.create(alice, new WithList(alice, elements))(
WithList.COMPANION
)
_ <- ledger.exercise(alice, contract.exerciseWithList_Noop())
} yield {
()
@ -57,9 +65,10 @@ final class LimitsIT extends LedgerTestSuite {
"Exercise a choice with a large list",
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, alice)) =>
val elements = (1 to 10000).map(e => f"element_$e%08d")
val elements = (1 to 10000).map(e => f"element_$e%08d").asJava
for {
contract <- ledger.create(alice, WithList(alice, List.empty[String]))
contract: WithList.ContractId <- ledger
.create(alice, new WithList(alice, List.empty[String].asJava))(WithList.COMPANION)
_ <- ledger.exercise(alice, contract.exerciseWithList_Expand(elements))
} yield {
()

View File

@ -3,7 +3,6 @@
package com.daml.ledger.api.testtool.suites.v1_15
import com.daml.ledger.api.refinements.ApiTypes
import com.daml.ledger.api.testtool.infrastructure.Allocation._
import com.daml.ledger.api.testtool.infrastructure.Assertions._
import com.daml.ledger.api.testtool.infrastructure.LedgerTestSuite
@ -12,16 +11,17 @@ import com.daml.ledger.api.v1.event_query_service.{
GetEventsByContractKeyRequest,
}
import com.daml.ledger.api.v1.value._
import com.daml.ledger.test.model.Test.{Dummy, _}
import com.daml.ledger.javaapi.data.Party
import com.daml.ledger.test.java.model.test.{Dummy, _}
import com.daml.lf.value.Value.ContractId
import scalapb.GeneratedMessage
import scalaz.Tag
import scalaz.syntax.tag.ToTagOps
import scala.collection.immutable
import java.util.{List => JList}
import scala.jdk.CollectionConverters._
import scala.concurrent.Future
class EventQueryServiceIT extends LedgerTestSuite {
import com.daml.ledger.api.testtool.suites.v1_8.CompanionImplicits._
private def toOption(protoString: String): Option[String] = {
if (protoString.nonEmpty) Some(protoString) else None
@ -30,12 +30,12 @@ class EventQueryServiceIT extends LedgerTestSuite {
// Note that the Daml template must be inspected to establish the key type and fields
// For the TextKey template the key is: (tkParty, tkKey) : (Party, Text)
// When populating the Record identifiers are not required.
private def makeTextKeyKey(party: ApiTypes.Party, keyText: String) = {
private def makeTextKeyKey(party: Party, keyText: String) = {
Value(
Value.Sum.Record(
Record(fields =
Vector(
RecordField(value = Some(Value(Value.Sum.Party(party.unwrap)))),
RecordField(value = Some(Value(Value.Sum.Party(party)))),
RecordField(value = Some(Value(Value.Sum.Text(keyText)))),
)
)
@ -50,14 +50,14 @@ class EventQueryServiceIT extends LedgerTestSuite {
)(implicit ec => { case Participants(Participant(ledger, party)) =>
for {
tx <- ledger.submitAndWaitForTransaction(
ledger.submitAndWaitRequest(party, Dummy(party).create.command)
ledger.submitAndWaitRequest(party, new Dummy(party).create.commands)
)
expected = assertDefined(
tx.transaction.flatMap(_.events.flatMap(_.event.created).headOption),
"Expected a created event",
)
events <- ledger.getEventsByContractId(
GetEventsByContractIdRequest(expected.contractId, Tag.unsubst(immutable.Seq(party)))
GetEventsByContractIdRequest(expected.contractId, Seq(party))
)
} yield {
val actual = assertDefined(events.createEvent, "Expected a created event")
@ -71,16 +71,16 @@ class EventQueryServiceIT extends LedgerTestSuite {
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
for {
dummyCid <- ledger.create(party, Dummy(party))
dummyCid <- ledger.create(party, new Dummy(party))
tx <- ledger.submitAndWaitForTransaction(
ledger.submitAndWaitRequest(party, dummyCid.exerciseDummyChoice1().command)
ledger.submitAndWaitRequest(party, dummyCid.exerciseDummyChoice1().commands)
)
expected = assertDefined(
tx.getTransaction.events.flatMap(_.event.archived).headOption,
"Expected an exercised event",
)
events <- ledger.getEventsByContractId(
GetEventsByContractIdRequest(dummyCid.unwrap, immutable.Seq(party.unwrap))
GetEventsByContractIdRequest(dummyCid.contractId, Seq(party))
)
} yield {
assertDefined(events.createEvent, "Expected a create event")
@ -97,7 +97,7 @@ class EventQueryServiceIT extends LedgerTestSuite {
val nonExistentContractId = ContractId.V1.assertFromString("00" * 32 + "0001")
for {
events <- ledger.getEventsByContractId(
GetEventsByContractIdRequest(nonExistentContractId.coid, Tag.unsubst(immutable.Seq(party)))
GetEventsByContractIdRequest(nonExistentContractId.coid, Seq(party))
)
} yield {
assertIsEmpty(Seq(events.createEvent, events.archiveEvent).flatten[GeneratedMessage])
@ -111,7 +111,7 @@ class EventQueryServiceIT extends LedgerTestSuite {
)(implicit ec => { case Participants(Participant(ledger, party, notTheSubmittingParty)) =>
for {
tx <- ledger.submitAndWaitForTransaction(
ledger.submitAndWaitRequest(party, Dummy(party).create.command)
ledger.submitAndWaitRequest(party, new Dummy(party).create.commands)
)
expected = assertDefined(
tx.transaction.flatMap(_.events.flatMap(_.event.created).headOption),
@ -120,7 +120,7 @@ class EventQueryServiceIT extends LedgerTestSuite {
events <- ledger.getEventsByContractId(
GetEventsByContractIdRequest(
expected.contractId,
immutable.Seq(notTheSubmittingParty.unwrap),
Seq(notTheSubmittingParty),
)
)
} yield {
@ -138,7 +138,7 @@ class EventQueryServiceIT extends LedgerTestSuite {
for {
tx <- ledger.submitAndWaitForTransaction(
ledger.submitAndWaitRequest(party, TextKey(party, someKey, Nil).create.command)
ledger.submitAndWaitRequest(party, new TextKey(party, someKey, JList.of()).create.commands)
)
expected = assertDefined(
tx.transaction.flatMap(_.events.flatMap(_.event.created).headOption),
@ -148,8 +148,8 @@ class EventQueryServiceIT extends LedgerTestSuite {
events <- ledger.getEventsByContractKey(
GetEventsByContractKeyRequest(
contractKey = Some(key),
templateId = Some(TextKey.id.unwrap),
requestingParties = Tag.unsubst(immutable.Seq(party)),
templateId = Some(TextKey.TEMPLATE_ID.toV1),
requestingParties = Seq(party),
)
)
} yield {
@ -167,9 +167,9 @@ class EventQueryServiceIT extends LedgerTestSuite {
val key = makeTextKeyKey(party, someKey)
for {
cId <- ledger.create(party, TextKey(party, someKey, Nil))
cId: TextKey.ContractId <- ledger.create(party, new TextKey(party, someKey, JList.of()))
tx <- ledger.submitAndWaitForTransaction(
ledger.submitAndWaitRequest(party, cId.exerciseTextKeyChoice().command)
ledger.submitAndWaitRequest(party, cId.exerciseTextKeyChoice().commands)
)
expected = assertDefined(
tx.transaction.flatMap(_.events.flatMap(_.event.archived).headOption),
@ -178,8 +178,8 @@ class EventQueryServiceIT extends LedgerTestSuite {
events <- ledger.getEventsByContractKey(
GetEventsByContractKeyRequest(
contractKey = Some(key),
templateId = Some(TextKey.id.unwrap),
requestingParties = Tag.unsubst(immutable.Seq(party)),
templateId = Some(TextKey.TEMPLATE_ID.toV1),
requestingParties = Seq(party),
)
)
} yield {
@ -200,8 +200,8 @@ class EventQueryServiceIT extends LedgerTestSuite {
events <- ledger.getEventsByContractKey(
GetEventsByContractKeyRequest(
contractKey = Some(key),
templateId = Some(TextKey.id.unwrap),
requestingParties = Tag.unsubst(immutable.Seq(party)),
templateId = Some(TextKey.TEMPLATE_ID.toV1),
requestingParties = Seq(party),
)
)
} yield {
@ -219,14 +219,17 @@ class EventQueryServiceIT extends LedgerTestSuite {
for {
_ <- ledger.submitAndWaitForTransaction(
ledger.submitAndWaitRequest(party, TextKey(party, nonVisibleKey, Nil).create.command)
ledger.submitAndWaitRequest(
party,
new TextKey(party, nonVisibleKey, JList.of()).create.commands,
)
)
events <- ledger.getEventsByContractKey(
GetEventsByContractKeyRequest(
contractKey = Some(key),
templateId = Some(TextKey.id.unwrap),
requestingParties = immutable.Seq(notTheSubmittingParty.unwrap),
templateId = Some(TextKey.TEMPLATE_ID.toV1),
requestingParties = Seq(notTheSubmittingParty),
)
)
} yield {
@ -247,8 +250,8 @@ class EventQueryServiceIT extends LedgerTestSuite {
.getEventsByContractKey(
GetEventsByContractKeyRequest(
contractKey = Some(key),
templateId = Some(TextKey.id.unwrap),
requestingParties = Tag.unsubst(immutable.Seq(party)),
templateId = Some(TextKey.TEMPLATE_ID.toV1),
requestingParties = Seq(party),
continuationToken = continuationToken.getOrElse(
GetEventsByContractKeyRequest.defaultInstance.continuationToken
),
@ -258,13 +261,19 @@ class EventQueryServiceIT extends LedgerTestSuite {
}
for {
textKeyCid1 <- ledger.create(party, TextKey(party, exercisedKey, Nil))
_ <- ledger.submitAndWaitForTransaction(
ledger.submitAndWaitRequest(party, textKeyCid1.exerciseTextKeyChoice().command)
textKeyCid1: TextKey.ContractId <- ledger.create(
party,
new TextKey(party, exercisedKey, Nil.asJava),
)
textKeyCid2 <- ledger.create(party, TextKey(party, exercisedKey, Nil))
_ <- ledger.submitAndWaitForTransaction(
ledger.submitAndWaitRequest(party, textKeyCid2.exerciseTextKeyChoice().command)
ledger.submitAndWaitRequest(party, textKeyCid1.exerciseTextKeyChoice().commands)
)
textKeyCid2: TextKey.ContractId <- ledger.create(
party,
new TextKey(party, exercisedKey, Nil.asJava),
)
_ <- ledger.submitAndWaitForTransaction(
ledger.submitAndWaitRequest(party, textKeyCid2.exerciseTextKeyChoice().commands)
)
eventId1 <- getNextResult(None)
eventId2 <- getNextResult(Some(assertDefined(eventId1, "Expected eventId2")))
@ -290,8 +299,8 @@ class EventQueryServiceIT extends LedgerTestSuite {
.getEventsByContractKey(
GetEventsByContractKeyRequest(
contractKey = Some(key),
templateId = Some(TextKey.id.unwrap),
requestingParties = Tag.unsubst(immutable.Seq(party)),
templateId = Some(TextKey.TEMPLATE_ID.toV1),
requestingParties = Seq(party),
continuationToken = continuationToken.getOrElse(
GetEventsByContractKeyRequest.defaultInstance.continuationToken
),
@ -301,11 +310,14 @@ class EventQueryServiceIT extends LedgerTestSuite {
}
for {
expected <- ledger.create(party, TextKey(party, exercisedKey, Nil))
expected: TextKey.ContractId <- ledger.create(
party,
new TextKey(party, exercisedKey, Nil.asJava),
)
_ <- ledger.submitAndWaitForTransaction(
ledger.submitAndWaitRequest(
party,
expected.exerciseTextKeyDisclose(tkNewDisclosedTo = immutable.Seq.empty).command,
expected.exerciseTextKeyDisclose(JList.of(): JList[String]).commands,
)
)
(cId2, token2) <- getNextResult(None)
@ -313,7 +325,7 @@ class EventQueryServiceIT extends LedgerTestSuite {
(cId0, _) <- getNextResult(token1)
} yield {
assertEquals("Expected the first offset to be empty", cId2.isDefined, true)
assertEquals("Expected the final offset to be empty", cId1, Some(expected))
assertEquals("Expected the final offset to be empty", cId1, Some(expected.contractId))
assertEquals("Expected the final offset to be empty", cId0.isDefined, false)
}
})

View File

@ -4,20 +4,15 @@
package com.daml.ledger.api.testtool.suites.v1_15
import com.daml.error.definitions.LedgerApiErrors
import com.daml.ledger.api.refinements.ApiTypes.Party
import com.daml.ledger.api.testtool.infrastructure.Allocation._
import com.daml.ledger.api.testtool.infrastructure.Assertions._
import com.daml.ledger.api.testtool.infrastructure.LedgerTestSuite
import com.daml.ledger.api.testtool.infrastructure.Synchronize.synchronize
import com.daml.ledger.api.testtool.infrastructure.TransactionHelpers.createdEvents
import com.daml.ledger.api.testtool.infrastructure.participant.ParticipantTestContext
import com.daml.ledger.javaapi.data.{CreateCommand, DamlRecord, ExerciseByKeyCommand, Party}
import com.daml.ledger.api.v1.command_service.SubmitAndWaitRequest
import com.daml.ledger.api.v1.commands.{
Command,
CreateCommand,
DisclosedContract,
ExerciseByKeyCommand,
}
import com.daml.ledger.api.v1.commands.DisclosedContract
import com.daml.ledger.api.v1.event.CreatedEvent
import com.daml.ledger.api.v1.transaction_filter.{
Filters,
@ -25,14 +20,14 @@ import com.daml.ledger.api.v1.transaction_filter.{
TemplateFilter,
TransactionFilter,
}
import com.daml.ledger.api.v1.value.{Identifier, Record, RecordField, Value}
import com.daml.ledger.client.binding
import com.daml.ledger.client.binding.Primitive
import com.daml.ledger.test.model.Test._
import com.daml.ledger.api.v1.value.Identifier
import com.daml.ledger.test.java.model.test._
import com.daml.ledger.javaapi
import com.daml.lf.transaction.TransactionCoder
import com.google.protobuf.ByteString
import scalaz.syntax.tag._
import com.daml.ledger.api.testtool.suites.v1_8.CompanionImplicits._
import java.util.{List => JList}
import scala.concurrent.{ExecutionContext, Future}
import scala.util.{Success, Try}
@ -100,9 +95,11 @@ final class ExplicitDisclosureIT extends LedgerTestSuite {
transactionFilter = filterByPartyAndTemplate(owner),
)
dummyCid <- ownerParticipant.create(owner, Dummy(owner))
dummyCid: Dummy.ContractId <- ownerParticipant.create(owner, new Dummy(owner))
dummyTxs <- ownerParticipant.flatTransactions(
ownerParticipant.getTransactionsRequest(filterByPartyAndTemplate(owner, Dummy.id.unwrap))
ownerParticipant.getTransactionsRequest(
filterByPartyAndTemplate(owner, Dummy.TEMPLATE_ID)
)
)
dummyCreate = createdEvents(dummyTxs(0)).head
dummyDisclosedContract = createEventToDisclosedContract(dummyCreate)
@ -146,11 +143,11 @@ final class ExplicitDisclosureIT extends LedgerTestSuite {
for {
// Create contract with `owner` as only stakeholder
_ <- ownerParticipant.submitAndWait(
ownerParticipant.submitAndWaitRequest(owner, WithKey(owner).create.command)
ownerParticipant.submitAndWaitRequest(owner, new WithKey(owner).create.commands)
)
txs <- ownerParticipant.flatTransactions(
ownerParticipant.getTransactionsRequest(
filterByPartyAndTemplate(owner, WithKey.id.unwrap)
filterByPartyAndTemplate(owner, WithKey.TEMPLATE_ID)
)
)
withKeyCreationTx = assertSingleton("Transaction expected non-empty", txs)
@ -232,9 +229,9 @@ final class ExplicitDisclosureIT extends LedgerTestSuite {
.traverse((1 to attempts).toList) {
_ =>
for {
contractId <- ledger1.create(party1, Dummy(party1))
contractId: Dummy.ContractId <- ledger1.create(party1, new Dummy(party1))
transactions <- ledger1.flatTransactionsByTemplateId(Dummy.id, party1)
transactions <- ledger1.flatTransactionsByTemplateId(Dummy.TEMPLATE_ID, party1)
create = createdEvents(transactions(0)).head
disclosedContract = createEventToDisclosedContract(create)
@ -245,7 +242,7 @@ final class ExplicitDisclosureIT extends LedgerTestSuite {
party2_exerciseWithDisclosureF =
ledger2.submitAndWait(
ledger2
.submitAndWaitRequest(party2, contractId.exercisePublicChoice(party2).command)
.submitAndWaitRequest(party2, contractId.exercisePublicChoice(party2).commands)
.update(_.commands.disclosedContracts := scala.Seq(disclosedContract))
)
@ -501,11 +498,11 @@ object ExplicitDisclosureIT {
case class TestContext(
ownerParticipant: ParticipantTestContext,
delegateParticipant: ParticipantTestContext,
owner: binding.Primitive.Party,
delegate: binding.Primitive.Party,
owner: Party,
delegate: Party,
contractKey: String,
delegationCid: binding.Primitive.ContractId[Delegation],
delegatedCid: binding.Primitive.ContractId[Delegated],
delegationCid: Delegation.ContractId,
delegatedCid: Delegated.ContractId,
originalCreateEvent: CreatedEvent,
disclosedContract: DisclosedContract,
) {
@ -517,7 +514,7 @@ object ExplicitDisclosureIT {
val request = delegateParticipant
.submitAndWaitRequest(
delegate,
delegationCid.exerciseFetchDelegated(delegatedCid).command,
delegationCid.exerciseFetchDelegated(delegatedCid).commands,
)
.update(_.commands.disclosedContracts := disclosedContracts)
delegateParticipant.submitAndWait(request)
@ -527,12 +524,10 @@ object ExplicitDisclosureIT {
val request = delegateParticipant
.submitAndWaitRequest(
delegate,
Command.of(
Command.Command.Create(
CreateCommand(
Some(Dummy.id.unwrap),
Some(Dummy(delegate).arguments),
)
JList.of(
new CreateCommand(
Dummy.TEMPLATE_ID,
new Dummy(delegate.getValue).toValue,
)
),
)
@ -545,8 +540,8 @@ object ExplicitDisclosureIT {
private def initializeTest(
ownerParticipant: ParticipantTestContext,
delegateParticipant: ParticipantTestContext,
owner: binding.Primitive.Party,
delegate: binding.Primitive.Party,
owner: Party,
delegate: Party,
transactionFilter: TransactionFilter,
)(implicit ec: ExecutionContext): Future[TestContext] = {
val contractKey = ownerParticipant.nextKeyId()
@ -554,11 +549,14 @@ object ExplicitDisclosureIT {
for {
// Create a Delegation contract
// Contract is visible both to owner (as signatory) and delegate (as observer)
delegationCid <- ownerParticipant.create(owner, Delegation(owner, delegate))
delegationCid <- ownerParticipant.create(
owner,
new Delegation(owner.getValue, delegate.getValue),
)
// Create Delegated contract
// This contract is only visible to the owner
delegatedCid <- ownerParticipant.create(owner, Delegated(owner, contractKey))
delegatedCid <- ownerParticipant.create(owner, new Delegated(owner.getValue, contractKey))
// Get the contract payload from the transaction stream of the owner
delegatedTx <- ownerParticipant.flatTransactions(
@ -582,20 +580,23 @@ object ExplicitDisclosureIT {
}
private def filterByPartyAndTemplate(
owner: binding.Primitive.Party,
templateId: Identifier = Delegated.id.unwrap,
): TransactionFilter =
owner: Party,
templateId: javaapi.data.Identifier = Delegated.TEMPLATE_ID,
): TransactionFilter = {
val templateIdScalaPB = Identifier.fromJavaProto(templateId.toProto)
new TransactionFilter(
Map(
owner.unwrap -> new Filters(
owner.getValue -> new Filters(
Some(
InclusiveFilters(templateFilters =
Seq(TemplateFilter(Some(templateId), includeCreatedEventBlob = true))
Seq(TemplateFilter(Some(templateIdScalaPB), includeCreatedEventBlob = true))
)
)
)
)
)
}
private def createEventToDisclosedContract(ev: CreatedEvent): DisclosedContract =
DisclosedContract(
@ -606,30 +607,21 @@ object ExplicitDisclosureIT {
private def exerciseWithKey_byKey_request(
ledger: ParticipantTestContext,
owner: Primitive.Party,
party: Primitive.Party,
owner: Party,
party: Party,
withKeyDisclosedContract: Option[DisclosedContract],
): SubmitAndWaitRequest =
ledger
.submitAndWaitRequest(
party,
Command.of(
Command.Command.ExerciseByKey(
ExerciseByKeyCommand(
Some(WithKey.id.unwrap),
Option(Value(Value.Sum.Party(Party.unwrap(owner)))),
"WithKey_NoOp",
Option(
Value(
Value.Sum.Record(
Record(
None,
List(RecordField("", Some(Value(Value.Sum.Party(Party.unwrap(party)))))),
)
)
)
),
)
JList.of(
new ExerciseByKeyCommand(
WithKey.TEMPLATE_ID,
owner,
"WithKey_NoOp",
new DamlRecord(
new DamlRecord.Field(party)
),
)
),
)

View File

@ -13,36 +13,39 @@ import com.daml.ledger.api.testtool.infrastructure.Allocation.{
import com.daml.ledger.api.testtool.infrastructure.Assertions._
import com.daml.ledger.api.testtool.infrastructure.LedgerTestSuite
import com.daml.ledger.api.testtool.infrastructure.TransactionHelpers._
import com.daml.ledger.api.v1.value.{Identifier, Value}
import com.daml.ledger.client.binding.Primitive
import com.daml.ledger.test.semantic.Interface._
import com.daml.ledger.test.semantic.{Interface1, Interface2, Interface3}
import scalaz.Tag
import com.daml.ledger.javaapi.data.{Command, DamlRecord, ExerciseCommand, Identifier}
import com.daml.ledger.javaapi.data.codegen.{ContractCompanion, Update}
import com.daml.ledger.test.java.semantic.interface$._
import com.daml.ledger.test.java.semantic.{interface1, interface2, interface3}
import java.util.{List => JList}
import scala.jdk.CollectionConverters._
class InterfaceIT extends LedgerTestSuite {
implicit val tCompanion: ContractCompanion.WithKey[T.Contract, T.ContractId, T, String] =
T.COMPANION
private[this] val TId = Tag.unwrap(T.id)
private[this] val I1Id = Tag.unwrap(Interface1.I.id)
private[this] val I2Id = Tag.unwrap(Interface2.I.id)
private[this] val I3Id = Tag.unwrap(Interface3.I.id)
private[this] val TId = T.TEMPLATE_ID
private[this] val I1Id = interface1.I.TEMPLATE_ID.toV1
private[this] val I2Id = interface2.I.TEMPLATE_ID
private[this] val I3Id = interface3.I.TEMPLATE_ID.toV1
// replace identifier with the wrong identifier for some of these tests
private[this] def useWrongId[X](
command: Primitive.Update[X],
update: Update[X],
id: Identifier,
): Primitive.Update[X] = {
val exe = command.command.getExercise
val arg = exe.getChoiceArgument.getRecord
command
.copy(
command = command.command.withExercise(
exe.copy(
templateId = Some(id),
choiceArgument = Some(Value.of(Value.Sum.Record(arg.copy(recordId = None)))),
)
)
): JList[Command] = {
val command = update.commands.asScala.head
val exe = command.asExerciseCommand.get
val arg = exe.getChoiceArgument.asRecord.get
JList.of(
new ExerciseCommand(
id,
exe.getContractId,
exe.getChoice,
new DamlRecord(arg.getFields),
)
.asInstanceOf[Primitive.Update[X]]
)
}
test(
@ -51,7 +54,7 @@ class InterfaceIT extends LedgerTestSuite {
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
for {
t <- ledger.create(party, T(party))
t <- ledger.create(party, new T(party))
tree <- ledger.exercise(party, t.exerciseMyArchive())
} yield {
val events = exercisedEvents(tree)
@ -67,8 +70,8 @@ class InterfaceIT extends LedgerTestSuite {
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
for {
t <- ledger.create(party, T(party))
tree <- ledger.exercise(party, t.toInterface[Interface1.I].exerciseMyArchive())
t <- ledger.create(party, new T(party))
tree <- ledger.exercise(party, t.toInterface(interface1.I.INTERFACE).exerciseMyArchive())
} yield {
val events = exercisedEvents(tree)
assertLength(s"1 successful exercise", 1, events)
@ -83,10 +86,10 @@ class InterfaceIT extends LedgerTestSuite {
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
for {
t <- ledger.create(party, T(party))
t <- ledger.create(party, new T(party))
tree <-
ledger
.exercise(party, t.asInstanceOf[Primitive.ContractId[Interface3.I]].exerciseMyArchive())
.exercise(party, (new interface3.I.ContractId(t.contractId)).exerciseMyArchive())
} yield {
val events = exercisedEvents(tree)
assertLength(s"1 successful exercise", 1, events)
@ -101,9 +104,14 @@ class InterfaceIT extends LedgerTestSuite {
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
for {
t <- ledger.create(party, T(party))
t <- ledger.create(party, new T(party))
failure <- ledger
.exercise(party, useWrongId(t.toInterface[Interface1.I].exerciseChoiceI1(), TId))
.submitAndWaitForTransactionTree(
ledger.submitAndWaitRequest(
party,
useWrongId(t.toInterface(interface1.I.INTERFACE).exerciseChoiceI1(), TId),
)
)
.mustFail("unknown choice")
} yield {
assertGrpcError(
@ -121,9 +129,14 @@ class InterfaceIT extends LedgerTestSuite {
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
for {
t <- ledger.create(party, T(party))
t <- ledger.create(party, new T(party))
failure <- ledger
.exercise(party, useWrongId(t.toInterface[Interface1.I].exerciseChoiceI1(), I2Id))
.submitAndWaitForTransactionTree(
ledger.submitAndWaitRequest(
party,
useWrongId(t.toInterface(interface1.I.INTERFACE).exerciseChoiceI1(), I2Id),
)
)
.mustFail("unknown choice")
} yield {
assertGrpcError(

View File

@ -4,7 +4,6 @@
package com.daml.ledger.api.testtool.suites.v1_15
import com.daml.error.definitions.LedgerApiErrors
import com.daml.ledger.api.refinements.ApiTypes.TemplateId
import com.daml.ledger.api.testtool.infrastructure.Allocation.{
Participant,
Participants,
@ -21,18 +20,15 @@ import com.daml.ledger.api.v1.event.{CreatedEvent, InterfaceView}
import com.daml.ledger.api.v1.transaction.Transaction
import com.daml.ledger.api.v1.transaction_filter.TransactionFilter
import com.daml.ledger.api.v1.value.{Identifier, Record}
import com.daml.ledger.test.semantic.InterfaceViews._
import com.daml.ledger.test.{
Carbonv1TestDar,
Carbonv2TestDar,
Carbonv3TestDar,
carbonv1,
carbonv2,
carbonv3,
}
import com.daml.ledger.test.java.semantic.interfaceviews.{T2, T3, T4, _}
import com.daml.ledger.javaapi
import com.daml.ledger.javaapi.data.codegen.ContractCompanion
import com.daml.ledger.test.java.semantic.da.types
import com.daml.ledger.test.java.{carbonv1, carbonv2, carbonv3}
import com.daml.ledger.test.{Carbonv1TestDar, Carbonv2TestDar, Carbonv3TestDar}
import com.daml.logging.LoggingContext
import scalaz.Tag
import java.lang
import java.util.regex.Pattern
import scala.concurrent.duration._
@ -43,6 +39,21 @@ class InterfaceSubscriptionsWithEventBlobsIT extends InterfaceSubscriptionsITBas
abstract class InterfaceSubscriptionsITBase(prefix: String, useTemplateIdBasedLegacyFormat: Boolean)
extends LedgerTestSuite {
implicit val t1Companion
: ContractCompanion.WithKey[T1.Contract, T1.ContractId, T1, types.Tuple2[String, lang.Long]] =
T1.COMPANION
implicit val t2Companion
: ContractCompanion.WithKey[T2.Contract, T2.ContractId, T2, types.Tuple2[String, lang.Long]] =
T2.COMPANION
implicit val t3Companion: ContractCompanion.WithoutKey[T3.Contract, T3.ContractId, T3] =
T3.COMPANION
implicit val t4Companion: ContractCompanion.WithoutKey[T4.Contract, T4.ContractId, T4] =
T4.COMPANION
implicit val t5Companion: ContractCompanion.WithoutKey[T5.Contract, T5.ContractId, T5] =
T5.COMPANION
implicit val t6Companion: ContractCompanion.WithoutKey[T6.Contract, T6.ContractId, T6] =
T6.COMPANION
test(
s"${prefix}TransactionsBasic",
"Basic functionality for interface subscriptions on transaction streams",
@ -51,22 +62,22 @@ abstract class InterfaceSubscriptionsITBase(prefix: String, useTemplateIdBasedLe
)(implicit ec => { case Participants(Participant(ledger, party)) =>
import ledger._
for {
c1 <- create(party, T1(party, 1))
c2 <- create(party, T2(party, 2))
c3 <- create(party, T3(party, 3))
_ <- create(party, T4(party, 4))
c1 <- create(party, new T1(party, 1))
c2 <- create(party, new T2(party, 2))
c3 <- create(party, new T3(party, 3))
_ <- create(party, new T4(party, 4))
transactions <- flatTransactions(
getTransactionsRequest(
transactionFilter(
Seq(party),
Seq(T1.id),
Seq((I.id, true)),
Seq(T1.TEMPLATE_ID),
Seq((I.TEMPLATE_ID, true)),
useTemplateIdBasedLegacyFormat,
)
)
)
events = transactions.flatMap(createdEvents)
} yield basicAssertions(c1.toString, c2.toString, c3.toString, events)
} yield basicAssertions(c1.contractId, c2.contractId, c3.contractId, events)
})
test(
@ -77,20 +88,20 @@ abstract class InterfaceSubscriptionsITBase(prefix: String, useTemplateIdBasedLe
)(implicit ec => { case Participants(Participant(ledger, party)) =>
import ledger._
for {
c1 <- create(party, T1(party, 1))
c2 <- create(party, T2(party, 2))
c3 <- create(party, T3(party, 3))
_ <- create(party, T4(party, 4))
c1 <- create(party, new T1(party, 1))
c2 <- create(party, new T2(party, 2))
c3 <- create(party, new T3(party, 3))
_ <- create(party, new T4(party, 4))
(_, createdEvents) <- activeContracts(
activeContractsRequest(
Seq(party),
Seq(T1.id),
Seq((I.id, true)),
Seq(T1.TEMPLATE_ID),
Seq((I.TEMPLATE_ID, true)),
"",
useTemplateIdBasedLegacyFormat,
)
)
} yield basicAssertions(c1.toString, c2.toString, c3.toString, createdEvents)
} yield basicAssertions(c1.contractId, c2.contractId, c3.contractId, createdEvents)
})
private def basicAssertions(
@ -107,10 +118,10 @@ abstract class InterfaceSubscriptionsITBase(prefix: String, useTemplateIdBasedLe
assertEquals(
"Create event 1 template ID",
createdEvent1.templateId.get.toString,
Tag.unwrap(T1.id).toString,
T1.TEMPLATE_ID.toV1.toString,
)
assertEquals("Create event 1 contract ID", createdEvent1.contractId, c1)
assertViewEquals(createdEvent1.interfaceViews, Tag.unwrap(I.id)) { value =>
assertViewEquals(createdEvent1.interfaceViews, I.TEMPLATE_ID.toV1) { value =>
assertLength("View1 has 2 fields", 2, value.fields)
assertEquals("View1.a", value.fields(0).getValue.getInt64, 1)
assertEquals("View1.b", value.fields(1).getValue.getBool, true)
@ -140,10 +151,10 @@ abstract class InterfaceSubscriptionsITBase(prefix: String, useTemplateIdBasedLe
assertEquals(
"Create event 2 template ID",
createdEvent2.templateId.get.toString,
Tag.unwrap(T2.id).toString,
T2.TEMPLATE_ID.toV1.toString,
)
assertEquals("Create event 2 contract ID", createdEvent2.contractId, c2)
assertViewEquals(createdEvent2.interfaceViews, Tag.unwrap(I.id)) { value =>
assertViewEquals(createdEvent2.interfaceViews, I.TEMPLATE_ID.toV1) { value =>
assertLength("View2 has 2 fields", 2, value.fields)
assertEquals("View2.a", value.fields(0).getValue.getInt64, 2)
assertEquals("View2.b", value.fields(1).getValue.getBool, false)
@ -165,10 +176,10 @@ abstract class InterfaceSubscriptionsITBase(prefix: String, useTemplateIdBasedLe
assertEquals(
"Create event 3 template ID",
createdEvent3.templateId.get.toString,
Tag.unwrap(T3.id).toString,
T3.TEMPLATE_ID.toV1.toString,
)
assertEquals("Create event 3 contract ID", createdEvent3.contractId, c3)
assertViewFailed(createdEvent3.interfaceViews, Tag.unwrap(I.id))
assertViewFailed(createdEvent3.interfaceViews, I.TEMPLATE_ID.toV1)
assertEquals(
"Create event 3 createArguments must be empty",
createdEvent3.createArguments.isEmpty,
@ -184,19 +195,19 @@ abstract class InterfaceSubscriptionsITBase(prefix: String, useTemplateIdBasedLe
)(implicit ec => { case Participants(Participant(ledger, party1, party2)) =>
import ledger._
for {
c <- create(party1, T6(party1, party2))
c <- create(party1, new T6(party1, party2))
mergedTransactions <- flatTransactions(
getTransactionsRequest(
new TransactionFilter(
Map(
party1.toString -> filters(
party1.getValue -> filters(
Seq.empty,
Seq((I.id, true)),
Seq((I.TEMPLATE_ID, true)),
useTemplateIdBasedLegacyFormat,
),
party2.toString -> filters(
party2.getValue -> filters(
Seq.empty,
Seq((I2.id, true)),
Seq((I2.TEMPLATE_ID, true)),
useTemplateIdBasedLegacyFormat,
),
)
@ -208,9 +219,9 @@ abstract class InterfaceSubscriptionsITBase(prefix: String, useTemplateIdBasedLe
getTransactionsRequest(
new TransactionFilter(
Map(
party1.toString -> filters(
party1.getValue -> filters(
Seq.empty,
Seq((I.id, true)),
Seq((I.TEMPLATE_ID, true)),
useTemplateIdBasedLegacyFormat,
)
)
@ -220,22 +231,22 @@ abstract class InterfaceSubscriptionsITBase(prefix: String, useTemplateIdBasedLe
} yield {
assertLength("single transaction found", 1, mergedTransactions)
val createdEvent1 = createdEvents(mergedTransactions(0)).head
assertEquals("Create event 1 contract ID", createdEvent1.contractId, c.toString)
assertViewEquals(createdEvent1.interfaceViews, Tag.unwrap(I.id)) { value =>
assertEquals("Create event 1 contract ID", createdEvent1.contractId, c.contractId)
assertViewEquals(createdEvent1.interfaceViews, I.TEMPLATE_ID.toV1) { value =>
assertLength("View1 has 2 fields", 2, value.fields)
assertEquals("View1.a", value.fields(0).getValue.getInt64, 6)
assertEquals("View1.b", value.fields(1).getValue.getBool, true)
}
assertViewEquals(createdEvent1.interfaceViews, Tag.unwrap(I2.id)) { value =>
assertViewEquals(createdEvent1.interfaceViews, I2.TEMPLATE_ID.toV1) { value =>
assertLength("View2 has 1 field", 1, value.fields)
assertEquals("View2.c", value.fields(0).getValue.getInt64, 7)
}
assertLength("single transaction found", 1, party1Transactions)
val createdEvent2 = createdEvents(party1Transactions(0)).head
assertEquals("Create event 1 contract ID", createdEvent2.contractId, c.toString)
assertEquals("Create event 1 contract ID", createdEvent2.contractId, c.contractId)
assertLength("single view found", 1, createdEvent2.interfaceViews)
assertViewEquals(createdEvent2.interfaceViews, Tag.unwrap(I.id)) { value =>
assertViewEquals(createdEvent2.interfaceViews, I.TEMPLATE_ID.toV1) { value =>
assertLength("View1 has 2 fields", 2, value.fields)
assertEquals("View1.a", value.fields(0).getValue.getInt64, 6)
assertEquals("View1.b", value.fields(1).getValue.getBool, true)
@ -251,13 +262,13 @@ abstract class InterfaceSubscriptionsITBase(prefix: String, useTemplateIdBasedLe
)(implicit ec => { case Participants(Participant(ledger, party)) =>
import ledger._
for {
c <- create(party, T5(party, 31337))
c <- create(party, new T5(party, 31337))
transactions <- flatTransactions(
getTransactionsRequest(
transactionFilter(
Seq(party),
Seq.empty,
Seq((I.id, true), (I2.id, true)),
Seq((I.TEMPLATE_ID, true), (I2.TEMPLATE_ID, true)),
useTemplateIdBasedLegacyFormat,
)
)
@ -265,13 +276,13 @@ abstract class InterfaceSubscriptionsITBase(prefix: String, useTemplateIdBasedLe
} yield {
assertLength("single transaction found", 1, transactions)
val createdEvent = createdEvents(transactions(0)).head
assertEquals("Create event 1 contract ID", createdEvent.contractId, c.toString)
assertViewEquals(createdEvent.interfaceViews, Tag.unwrap(I.id)) { value =>
assertEquals("Create event 1 contract ID", createdEvent.contractId, c.contractId)
assertViewEquals(createdEvent.interfaceViews, I.TEMPLATE_ID.toV1) { value =>
assertLength("View1 has 2 fields", 2, value.fields)
assertEquals("View1.a", value.fields(0).getValue.getInt64, 31337)
assertEquals("View1.b", value.fields(1).getValue.getBool, true)
}
assertViewEquals(createdEvent.interfaceViews, Tag.unwrap(I2.id)) { value =>
assertViewEquals(createdEvent.interfaceViews, I2.TEMPLATE_ID.toV1) { value =>
assertLength("View2 has 1 field", 1, value.fields)
assertEquals("View2.c", value.fields(0).getValue.getInt64, 1)
}
@ -286,13 +297,13 @@ abstract class InterfaceSubscriptionsITBase(prefix: String, useTemplateIdBasedLe
)(implicit ec => { case Participants(Participant(ledger, party)) =>
import ledger._
for {
_ <- create(party, T4(party, 4))
_ <- create(party, new T4(party, 4))
transactions <- flatTransactions(
getTransactionsRequest(
transactionFilter(
Seq(party),
Seq.empty,
Seq((INoTemplate.id, true)),
Seq((INoTemplate.TEMPLATE_ID, true)),
useTemplateIdBasedLegacyFormat,
)
)
@ -311,16 +322,16 @@ abstract class InterfaceSubscriptionsITBase(prefix: String, useTemplateIdBasedLe
)(implicit ec => { case Participants(Participant(ledger, party)) =>
import ledger._
for {
c1 <- create(party, T1(party, 1))
c2 <- create(party, T2(party, 2))
c3 <- create(party, T3(party, 3))
_ <- create(party, T4(party, 4))
c1 <- create(party, new T1(party, 1))
c2 <- create(party, new T2(party, 2))
c3 <- create(party, new T3(party, 3))
_ <- create(party, new T4(party, 4))
transactions <- flatTransactions(
getTransactionsRequest(
transactionFilter(
Seq(party),
Seq(T1.id),
Seq((I.id, false), (I.id, true)),
Seq(T1.TEMPLATE_ID),
Seq((I.TEMPLATE_ID, false), (I.TEMPLATE_ID, true)),
useTemplateIdBasedLegacyFormat,
)
)
@ -328,12 +339,12 @@ abstract class InterfaceSubscriptionsITBase(prefix: String, useTemplateIdBasedLe
)
} yield {
val createdEvent1 = createdEvents(transactions(0)).head
assertEquals("Create event 1 contract ID", createdEvent1.contractId, c1.toString)
assertEquals("Create event 1 contract ID", createdEvent1.contractId, c1.contractId)
val createdEvent2 = createdEvents(transactions(1)).head
assertEquals("Create event 2 contract ID", createdEvent2.contractId, c2.toString)
assertEquals("Create event 2 contract ID", createdEvent2.contractId, c2.contractId)
// Expect view to be delivered even though there is an ambiguous
// includeInterfaceView flag set to true and false at the same time (true wins)
assertViewEquals(createdEvent2.interfaceViews, Tag.unwrap(I.id)) { value =>
assertViewEquals(createdEvent2.interfaceViews, I.TEMPLATE_ID.toV1) { value =>
assertLength("View2 has 2 fields", 2, value.fields)
assertEquals("View2.a", value.fields(0).getValue.getInt64, 2)
assertEquals("View2.b", value.fields(1).getValue.getBool, false)
@ -343,7 +354,7 @@ abstract class InterfaceSubscriptionsITBase(prefix: String, useTemplateIdBasedLe
)
}
val createdEvent3 = createdEvents(transactions(2)).head
assertEquals("Create event 3 contract ID", createdEvent3.contractId, c3.toString)
assertEquals("Create event 3 contract ID", createdEvent3.contractId, c3.contractId)
}
})
@ -355,39 +366,39 @@ abstract class InterfaceSubscriptionsITBase(prefix: String, useTemplateIdBasedLe
)(implicit ec => { case Participants(Participant(ledger, party)) =>
import ledger._
for {
c1 <- create(party, T1(party, 1))
c2 <- create(party, T2(party, 2))
c3 <- create(party, T3(party, 3))
_ <- create(party, T4(party, 4))
c1 <- create(party, new T1(party, 1))
c2 <- create(party, new T2(party, 2))
c3 <- create(party, new T3(party, 3))
_ <- create(party, new T4(party, 4))
transactions <- flatTransactions(
getTransactionsRequest(
transactionFilter(
Seq(party),
Seq(T1.id, T1.id),
Seq((I.id, true)),
Seq(T1.TEMPLATE_ID, T1.TEMPLATE_ID),
Seq((I.TEMPLATE_ID, true)),
useTemplateIdBasedLegacyFormat,
)
)
)
} yield {
val createdEvent1 = createdEvents(transactions(0)).head
assertEquals("Create event 1 contract ID", createdEvent1.contractId, c1.toString)
assertEquals("Create event 1 contract ID", createdEvent1.contractId, c1.contractId)
assertEquals(
"Create event 1 createArguments must NOT be empty",
createdEvent1.createArguments.isEmpty,
false,
)
val createdEvent2 = createdEvents(transactions(1)).head
assertEquals("Create event 2 contract ID", createdEvent2.contractId, c2.toString)
assertEquals("Create event 2 contract ID", createdEvent2.contractId, c2.contractId)
// Expect view to be delivered even though there is an ambiguous
// includeInterfaceView flag set to true and false at the same time.
assertViewEquals(createdEvent2.interfaceViews, Tag.unwrap(I.id)) { value =>
assertViewEquals(createdEvent2.interfaceViews, I.TEMPLATE_ID.toV1) { value =>
assertLength("View2 has 2 fields", 2, value.fields)
assertEquals("View2.a", value.fields(0).getValue.getInt64, 2)
assertEquals("View2.b", value.fields(1).getValue.getBool, false)
}
val createdEvent3 = createdEvents(transactions(2)).head
assertEquals("Create event 3 contract ID", createdEvent3.contractId, c3.toString)
assertEquals("Create event 3 contract ID", createdEvent3.contractId, c3.contractId)
}
})
@ -399,16 +410,16 @@ abstract class InterfaceSubscriptionsITBase(prefix: String, useTemplateIdBasedLe
)(implicit ec => { case Participants(Participant(ledger, party)) =>
import ledger._
for {
c1 <- create(party, T1(party, 1))
_ <- create(party, T2(party, 2))
_ <- create(party, T3(party, 3))
_ <- create(party, T4(party, 4))
c1 <- create(party, new T1(party, 1))
_ <- create(party, new T2(party, 2))
_ <- create(party, new T3(party, 3))
_ <- create(party, new T4(party, 4))
transactions <- flatTransactions(
getTransactionsRequest(
transactionFilter(
Seq(party),
Seq(T1.id),
Seq((I.id, false)),
Seq(T1.TEMPLATE_ID),
Seq((I.TEMPLATE_ID, false)),
useTemplateIdBasedLegacyFormat,
)
)
@ -427,9 +438,9 @@ abstract class InterfaceSubscriptionsITBase(prefix: String, useTemplateIdBasedLe
assertEquals(
"Create event 1 template ID",
createdEvent1.templateId.get.toString,
Tag.unwrap(T1.id).toString,
T1.TEMPLATE_ID.toV1.toString,
)
assertEquals("Create event 1 contract ID", createdEvent1.contractId, c1.toString)
assertEquals("Create event 1 contract ID", createdEvent1.contractId, c1.contractId)
assertEquals(
"Create event 1 createArguments must NOT be empty",
createdEvent1.createArguments.isEmpty,
@ -445,19 +456,19 @@ abstract class InterfaceSubscriptionsITBase(prefix: String, useTemplateIdBasedLe
enabled = _.templateFilters || useTemplateIdBasedLegacyFormat,
)(implicit ec => { case Participants(Participant(ledger, party)) =>
import ledger._
val allImplementations = Seq(T1.id, T2.id, T3.id)
val allImplementations = Seq(T1.TEMPLATE_ID, T2.TEMPLATE_ID, T3.TEMPLATE_ID)
for {
_ <- create(party, T1(party, 1))
_ <- create(party, T2(party, 2))
_ <- create(party, T3(party, 3))
_ <- create(party, T4(party, 4))
_ <- create(party, new T1(party, 1))
_ <- create(party, new T2(party, 2))
_ <- create(party, new T3(party, 3))
_ <- create(party, new T4(party, 4))
// 1. Subscribe by the interface
transactions1 <- flatTransactions(
getTransactionsRequest(
transactionFilter(
Seq(party),
Seq.empty,
Seq((I.id, true)),
Seq((I.TEMPLATE_ID, true)),
useTemplateIdBasedLegacyFormat,
)
)
@ -479,7 +490,7 @@ abstract class InterfaceSubscriptionsITBase(prefix: String, useTemplateIdBasedLe
transactionFilter(
Seq(party),
allImplementations,
Seq((I.id, true)),
Seq((I.TEMPLATE_ID, true)),
useTemplateIdBasedLegacyFormat,
)
)
@ -521,11 +532,14 @@ abstract class InterfaceSubscriptionsITBase(prefix: String, useTemplateIdBasedLe
allocate(SingleParty),
enabled = _.templateFilters || useTemplateIdBasedLegacyFormat,
)(implicit ec => { case Participants(Participant(ledger, party)) =>
val unknownTemplate = TemplateId(Tag.unwrap(I.id).copy(entityName = "TemplateDoesNotExist"))
val unknownInterface = TemplateId(Tag.unwrap(I.id).copy(entityName = "InterfaceDoesNotExist"))
val packageId = I.TEMPLATE_ID.getPackageId
val moduleName = I.TEMPLATE_ID.getModuleName
val unknownTemplate = new javaapi.data.Identifier(packageId, moduleName, "TemplateDoesNotExist")
val unknownInterface =
new javaapi.data.Identifier(packageId, moduleName, "InterfaceDoesNotExist")
import ledger._
for {
_ <- create(party, T1(party, 1))
_ <- create(party, new T1(party, 1))
failure <- flatTransactions(
getTransactionsRequest(
transactionFilter(
@ -570,13 +584,13 @@ abstract class InterfaceSubscriptionsITBase(prefix: String, useTemplateIdBasedLe
)(implicit ec => { case Participants(Participant(ledger, party1, party2)) =>
import ledger._
for {
_ <- create(party1, T6(party1, party2))
_ <- create(party1, new T6(party1, party2))
party1Iface1transactionsWithView <- flatTransactions(
getTransactionsRequest(
transactionFilter(
Seq(party1),
Seq.empty,
Seq((I.id, true)),
Seq((I.TEMPLATE_ID, true)),
useTemplateIdBasedLegacyFormat,
)
)
@ -586,7 +600,7 @@ abstract class InterfaceSubscriptionsITBase(prefix: String, useTemplateIdBasedLe
transactionFilter(
Seq(party1),
Seq.empty,
Seq((I.id, false)),
Seq((I.TEMPLATE_ID, false)),
useTemplateIdBasedLegacyFormat,
)
)
@ -596,7 +610,7 @@ abstract class InterfaceSubscriptionsITBase(prefix: String, useTemplateIdBasedLe
transactionFilter(
Seq(party2),
Seq.empty,
Seq((I.id, true)),
Seq((I.TEMPLATE_ID, true)),
useTemplateIdBasedLegacyFormat,
)
)
@ -606,7 +620,7 @@ abstract class InterfaceSubscriptionsITBase(prefix: String, useTemplateIdBasedLe
transactionFilter(
Seq(party2),
Seq.empty,
Seq((I.id, false)),
Seq((I.TEMPLATE_ID, false)),
useTemplateIdBasedLegacyFormat,
)
)
@ -660,7 +674,7 @@ abstract class InterfaceSubscriptionsITBase(prefix: String, useTemplateIdBasedLe
transactionFilter(
Seq(party),
Seq.empty,
Seq((carbonv1.CarbonV1.I.id, true)),
Seq((carbonv1.carbonv1.I.TEMPLATE_ID, true)),
useTemplateIdBasedLegacyFormat,
)
)
@ -681,16 +695,16 @@ abstract class InterfaceSubscriptionsITBase(prefix: String, useTemplateIdBasedLe
description = "Topology processing around Dar upload can take a bit of time.",
delayMechanism = ledger.delayMechanism,
) {
create(party, carbonv2.CarbonV2.T(party, 21))
create(party, new carbonv2.carbonv2.T(party, 21))(carbonv2.carbonv2.T.COMPANION)
}
transactions <- transactionFuture
} yield assertSingleContractWithSimpleView(
transactions = transactions,
contractIdentifier = Tag.unwrap(carbonv2.CarbonV2.T.id),
viewIdentifier = Tag.unwrap(carbonv1.CarbonV1.I.id),
contractId = contract.toString,
contractIdentifier = carbonv2.carbonv2.T.TEMPLATE_ID.toV1,
viewIdentifier = carbonv1.carbonv1.I.TEMPLATE_ID.toV1,
contractId = contract.contractId,
viewValue = 21,
)
})
@ -712,7 +726,7 @@ abstract class InterfaceSubscriptionsITBase(prefix: String, useTemplateIdBasedLe
description = "Topology processing around Dar upload can take a bit of time.",
delayMechanism = ledger.delayMechanism,
) {
create(party, carbonv2.CarbonV2.T(party, 77))
create(party, new carbonv2.carbonv2.T(party, 77))(carbonv2.carbonv2.T.COMPANION)
}
_ <- ledger.uploadDarFile(Dars.read(Carbonv3TestDar.path))
transactions <- flatTransactions(
@ -720,16 +734,16 @@ abstract class InterfaceSubscriptionsITBase(prefix: String, useTemplateIdBasedLe
transactionFilter(
Seq(party),
Seq.empty,
Seq((carbonv3.CarbonV3.RetroI.id, true)),
Seq((carbonv3.carbonv3.RetroI.TEMPLATE_ID, true)),
useTemplateIdBasedLegacyFormat,
)
)
)
} yield assertSingleContractWithSimpleView(
transactions = transactions,
contractIdentifier = Tag.unwrap(carbonv2.CarbonV2.T.id),
viewIdentifier = Tag.unwrap(carbonv3.CarbonV3.RetroI.id),
contractId = contract.toString,
contractIdentifier = carbonv2.carbonv2.T.TEMPLATE_ID.toV1,
viewIdentifier = carbonv3.carbonv3.RetroI.TEMPLATE_ID.toV1,
contractId = contract.contractId,
viewValue = 77,
)
})

View File

@ -18,9 +18,8 @@ import com.daml.ledger.api.v1.transaction_filter.{
TransactionFilter,
}
import com.daml.ledger.api.v1.value.Identifier
import com.daml.ledger.client.binding.Primitive
import com.daml.ledger.test.semantic.InterfaceViews._
import scalaz.Tag
import com.daml.ledger.javaapi.data.Party
import com.daml.ledger.test.java.semantic.interfaceviews._
import scala.concurrent.{ExecutionContext, Future}
@ -160,30 +159,30 @@ class TransactionServiceFiltersIT extends LedgerTestSuite {
private def testFilterComposition(
ledger: ParticipantTestContext,
party: Primitive.Party,
party: Party,
filter: TransactionFilter,
)(implicit ec: ExecutionContext): Future[Unit] = {
import ledger._
for {
c1 <- create(party, T5(party, 1))
c2 <- create(party, T6(party, party))
c3 <- create(party, T3(party, 2))
_ <- create(party, T4(party, 4))
c1 <- create(party, new T5(party, 1))(T5.COMPANION)
c2 <- create(party, new T6(party, party))(T6.COMPANION)
c3 <- create(party, new T3(party, 2))(T3.COMPANION)
_ <- create(party, new T4(party, 4))(T4.COMPANION)
txEvents <- flatTransactions(getTransactionsRequest(filter)).map(_.flatMap(createdEvents))
acsEvents <- activeContracts(createActiveContractsRequest(filter)).map(_._2)
} yield {
basicAssertions(
c1.toString,
c2.toString,
c3.toString,
c1.contractId,
c2.contractId,
c3.contractId,
txEvents,
eventBlobFlagFromInterfaces(filter),
eventBlobFlagFromTemplates(filter),
)
basicAssertions(
c1.toString,
c2.toString,
c3.toString,
c1.contractId,
c2.contractId,
c3.contractId,
acsEvents,
eventBlobFlagFromInterfaces(filter),
eventBlobFlagFromTemplates(filter),
@ -221,8 +220,8 @@ class TransactionServiceFiltersIT extends LedgerTestSuite {
val createdEvent1 = createdEvents(0)
assertEquals(
"Create event 1 template ID",
createdEvent1.templateId.get.toString,
Tag.unwrap(T5.id).toString,
createdEvent1.templateId.get,
T5.TEMPLATE_ID.toV1,
)
assertEquals("Create event 1 contract ID", createdEvent1.contractId, c1)
assertLength("Create event 1 has a view", 1, createdEvent1.interfaceViews)
@ -241,8 +240,8 @@ class TransactionServiceFiltersIT extends LedgerTestSuite {
val createdEvent2 = createdEvents(1)
assertEquals(
"Create event 2 template ID",
createdEvent2.templateId.get.toString,
Tag.unwrap(T6.id).toString,
createdEvent2.templateId.get,
T6.TEMPLATE_ID.toV1,
)
assertEquals("Create event 2 contract ID", createdEvent2.contractId, c2)
assertLength("Create event 2 has a view", 1, createdEvent2.interfaceViews)
@ -263,7 +262,7 @@ class TransactionServiceFiltersIT extends LedgerTestSuite {
assertEquals(
"Create event 3 template ID",
createdEvent3.templateId.get.toString,
Tag.unwrap(T3.id).toString,
T3.TEMPLATE_ID.toV1.toString,
)
assertEquals("Create event 3 contract ID", createdEvent3.contractId, c3)
assertLength("Create event 3 has no view", 0, createdEvent3.interfaceViews)
@ -285,7 +284,7 @@ class TransactionServiceFiltersIT extends LedgerTestSuite {
) = {
Seq(
new InterfaceFilter(
interfaceId = Some(Tag.unwrap(I2.id)),
interfaceId = Some(I2.TEMPLATE_ID.toV1),
includeInterfaceView = true,
includeCreatedEventBlob = includeCreatedEventBlob,
)
@ -293,29 +292,29 @@ class TransactionServiceFiltersIT extends LedgerTestSuite {
}
private def createTemplateIdFilter: Seq[Identifier] =
Seq(Tag.unwrap(T3.id), Tag.unwrap(T5.id))
Seq(T3.TEMPLATE_ID.toV1, T5.TEMPLATE_ID.toV1)
private def createTemplateFilter(includeCreatedEventBlob: Boolean): Seq[TemplateFilter] =
Seq(
new TemplateFilter(
templateId = Some(Tag.unwrap(T3.id)),
templateId = Some(T3.TEMPLATE_ID.toV1),
includeCreatedEventBlob = includeCreatedEventBlob,
),
new TemplateFilter(
templateId = Some(Tag.unwrap(T5.id)),
templateId = Some(T5.TEMPLATE_ID.toV1),
includeCreatedEventBlob = includeCreatedEventBlob,
),
)
private def createTransactionFilter(
party: Primitive.Party,
party: Party,
interfaceFilters: Seq[InterfaceFilter],
templateIds: Seq[Identifier] = Seq.empty,
templateFilters: Seq[TemplateFilter] = Seq.empty,
): TransactionFilter =
new TransactionFilter(
filtersByParty = Map(
party.toString -> new Filters(
party.getValue -> new Filters(
inclusive = Some(
new InclusiveFilters(
templateIds = templateIds,

View File

@ -13,12 +13,9 @@ import com.daml.ledger.api.v1.event.Event.Event.Created
import com.daml.ledger.api.v1.event.{CreatedEvent, Event}
import com.daml.ledger.api.v1.transaction_filter.{Filters, InclusiveFilters, TransactionFilter}
import com.daml.ledger.api.v1.value.Identifier
import com.daml.ledger.client.binding.Primitive.{Party, TemplateId}
import com.daml.ledger.client.binding.{Primitive, Template}
import com.daml.ledger.test.model.Test.Divulgence2._
import com.daml.ledger.test.model.Test.Dummy._
import com.daml.ledger.test.model.Test.Witnesses._
import com.daml.ledger.test.model.Test.{
import com.daml.ledger.javaapi.data.{Identifier => JavaIdentifier}
import com.daml.ledger.javaapi.data.{Party, Template}
import com.daml.ledger.test.java.model.test.{
Divulgence1,
Divulgence2,
Dummy,
@ -29,13 +26,15 @@ import com.daml.ledger.test.model.Test.{
WithObservers,
Witnesses => TestWitnesses,
}
import scalaz.syntax.tag._
import com.daml.ledger.javaapi.data.codegen.ContractId
import scala.collection.immutable.Seq
import scala.concurrent.{ExecutionContext, Future}
import scala.jdk.CollectionConverters._
import scala.util.Random
class ActiveContractsServiceIT extends LedgerTestSuite {
import CompanionImplicits._
test(
"ACSinvalidLedgerId",
@ -90,19 +89,19 @@ class ActiveContractsServiceIT extends LedgerTestSuite {
)
assert(
activeContracts.exists(_.contractId == dummy),
activeContracts.exists(_.contractId == dummy.contractId),
s"Didn't find Dummy contract with contractId $dummy.",
)
assert(
activeContracts.exists(_.contractId == dummyWithParam),
activeContracts.exists(_.contractId == dummyWithParam.contractId),
s"Didn't find DummyWithParam contract with contractId $dummy.",
)
assert(
activeContracts.exists(_.contractId == dummyFactory),
activeContracts.exists(_.contractId == dummyFactory.contractId),
s"Didn't find DummyFactory contract with contractId $dummy.",
)
val invalidSignatories = activeContracts.filterNot(_.signatories == Seq(party.unwrap))
val invalidSignatories = activeContracts.filterNot(_.signatories == Seq(party.getValue))
assert(
invalidSignatories.isEmpty,
s"Found contracts with signatories other than $party: $invalidSignatories",
@ -123,7 +122,7 @@ class ActiveContractsServiceIT extends LedgerTestSuite {
)(implicit ec => { case Participants(Participant(ledger, party)) =>
for {
(dummy, _, _) <- createDummyContracts(party, ledger)
activeContracts <- ledger.activeContractsByTemplateId(Seq(Dummy.id), party)
activeContracts <- ledger.activeContractsByTemplateId(Seq(Dummy.TEMPLATE_ID), party)
} yield {
assert(
activeContracts.size == 1,
@ -131,11 +130,11 @@ class ActiveContractsServiceIT extends LedgerTestSuite {
)
assert(
activeContracts.head.getTemplateId == Dummy.id.unwrap,
activeContracts.head.getTemplateId == Identifier.fromJavaProto(Dummy.TEMPLATE_ID.toProto),
s"Received contract is not of type Dummy, but ${activeContracts.head.templateId}.",
)
assert(
activeContracts.head.contractId == dummy,
activeContracts.head.contractId == dummy.contractId,
s"Expected contract with contractId $dummy, but received ${activeContracts.head.contractId}.",
)
}
@ -159,7 +158,7 @@ class ActiveContractsServiceIT extends LedgerTestSuite {
)
assert(
contractsBeforeExercise.exists(_.contractId == dummy),
contractsBeforeExercise.exists(_.contractId == dummy.contractId),
s"Expected to receive contract with contractId $dummy, but received ${contractsBeforeExercise
.map(_.contractId)
.mkString(", ")} instead.",
@ -172,7 +171,7 @@ class ActiveContractsServiceIT extends LedgerTestSuite {
)
assert(
!contractsAfterExercise.exists(_.contractId == dummy),
!contractsAfterExercise.exists(_.contractId == dummy.contractId),
s"Expected to not receive contract with contractId $dummy.",
)
}
@ -184,21 +183,21 @@ class ActiveContractsServiceIT extends LedgerTestSuite {
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
for {
dummy <- ledger.create(party, Dummy(party))
dummy <- ledger.create(party, new Dummy(party))
(Some(offset), onlyDummy) <- ledger.activeContracts(
ledger.activeContractsRequest(
Seq(party),
useTemplateIdBasedLegacyFormat = !ledger.features.templateFilters,
)
)
dummyWithParam <- ledger.create(party, DummyWithParam(party))
dummyWithParam <- ledger.create(party, new DummyWithParam(party))
request = ledger.getTransactionsRequest(ledger.transactionFilter(Seq(party)))
fromOffset = request.update(_.begin := offset)
transactions <- ledger.flatTransactions(fromOffset)
} yield {
assert(onlyDummy.size == 1)
assert(
onlyDummy.exists(_.contractId == dummy),
onlyDummy.exists(_.contractId == dummy.contractId),
s"Expected to receive $dummy in active contracts, but didn't receive it.",
)
@ -217,7 +216,7 @@ class ActiveContractsServiceIT extends LedgerTestSuite {
createdEvent
}
assert(
createdEvent.exists(_.contractId == dummyWithParam),
createdEvent.exists(_.contractId == dummyWithParam.contractId),
s"Expected a CreateEvent for $dummyWithParam, but received $createdEvent.",
)
}
@ -229,7 +228,7 @@ class ActiveContractsServiceIT extends LedgerTestSuite {
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
for {
_ <- ledger.create(party, Dummy(party))
_ <- ledger.create(party, new Dummy(party))
verboseRequest = ledger
.activeContractsRequest(
Seq(party),
@ -265,9 +264,9 @@ class ActiveContractsServiceIT extends LedgerTestSuite {
allContractsForAlice <- ledger.activeContracts(alice)
allContractsForBob <- ledger.activeContracts(bob)
allContractsForAliceAndBob <- ledger.activeContracts(alice, bob)
dummyContractsForAlice <- ledger.activeContractsByTemplateId(Seq(Dummy.id), alice)
dummyContractsForAlice <- ledger.activeContractsByTemplateId(Seq(Dummy.TEMPLATE_ID), alice)
dummyContractsForAliceAndBob <- ledger.activeContractsByTemplateId(
Seq(Dummy.id),
Seq(Dummy.TEMPLATE_ID),
alice,
bob,
)
@ -276,37 +275,37 @@ class ActiveContractsServiceIT extends LedgerTestSuite {
allContractsForAlice.size == 3,
s"$alice expected 3 events, but received ${allContractsForAlice.size}.",
)
assertTemplates(Seq(alice), allContractsForAlice, Dummy.id, 1)
assertTemplates(Seq(alice), allContractsForAlice, DummyWithParam.id, 1)
assertTemplates(Seq(alice), allContractsForAlice, DummyFactory.id, 1)
assertTemplates(Seq(alice), allContractsForAlice, Dummy.TEMPLATE_ID, 1)
assertTemplates(Seq(alice), allContractsForAlice, DummyWithParam.TEMPLATE_ID, 1)
assertTemplates(Seq(alice), allContractsForAlice, DummyFactory.TEMPLATE_ID, 1)
assert(
allContractsForBob.size == 3,
s"$bob expected 3 events, but received ${allContractsForBob.size}.",
)
assertTemplates(Seq(bob), allContractsForBob, Dummy.id, 1)
assertTemplates(Seq(bob), allContractsForBob, DummyWithParam.id, 1)
assertTemplates(Seq(bob), allContractsForBob, DummyFactory.id, 1)
assertTemplates(Seq(bob), allContractsForBob, Dummy.TEMPLATE_ID, 1)
assertTemplates(Seq(bob), allContractsForBob, DummyWithParam.TEMPLATE_ID, 1)
assertTemplates(Seq(bob), allContractsForBob, DummyFactory.TEMPLATE_ID, 1)
assert(
allContractsForAliceAndBob.size == 6,
s"$alice and $bob expected 6 events, but received ${allContractsForAliceAndBob.size}.",
)
assertTemplates(Seq(alice, bob), allContractsForAliceAndBob, Dummy.id, 2)
assertTemplates(Seq(alice, bob), allContractsForAliceAndBob, DummyWithParam.id, 2)
assertTemplates(Seq(alice, bob), allContractsForAliceAndBob, DummyFactory.id, 2)
assertTemplates(Seq(alice, bob), allContractsForAliceAndBob, Dummy.TEMPLATE_ID, 2)
assertTemplates(Seq(alice, bob), allContractsForAliceAndBob, DummyWithParam.TEMPLATE_ID, 2)
assertTemplates(Seq(alice, bob), allContractsForAliceAndBob, DummyFactory.TEMPLATE_ID, 2)
assert(
dummyContractsForAlice.size == 1,
s"$alice expected 1 event, but received ${dummyContractsForAlice.size}.",
)
assertTemplates(Seq(alice), dummyContractsForAlice, Dummy.id, 1)
assertTemplates(Seq(alice), dummyContractsForAlice, Dummy.TEMPLATE_ID, 1)
assert(
dummyContractsForAliceAndBob.size == 2,
s"$alice and $bob expected 2 events, but received ${dummyContractsForAliceAndBob.size}.",
)
assertTemplates(Seq(alice, bob), dummyContractsForAliceAndBob, Dummy.id, 2)
assertTemplates(Seq(alice, bob), dummyContractsForAliceAndBob, Dummy.TEMPLATE_ID, 2)
}
})
@ -316,16 +315,16 @@ class ActiveContractsServiceIT extends LedgerTestSuite {
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
for {
dummyCid <- ledger.create(party, Dummy(party))
dummyWithParamCid <- ledger.create(party, DummyWithParam(party))
dummyCid <- ledger.create(party, new Dummy(party))
dummyWithParamCid <- ledger.create(party, new DummyWithParam(party))
contracts <- ledger.activeContracts(party)
} yield {
assert(contracts.size == 2, s"$party expected 2 contracts, but received ${contracts.size}.")
val dummyAgreementText = contracts.collect {
case ev if ev.contractId == dummyCid => ev.agreementText
case ev if ev.contractId == dummyCid.contractId => ev.agreementText
}
val dummyWithParamAgreementText = contracts.collect {
case ev if ev.contractId == dummyWithParamCid => ev.agreementText
case ev if ev.contractId == dummyWithParamCid.contractId => ev.agreementText
}
assert(
@ -345,7 +344,7 @@ class ActiveContractsServiceIT extends LedgerTestSuite {
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
for {
_ <- ledger.create(party, Dummy(party))
_ <- ledger.create(party, new Dummy(party))
Vector(dummyEvent) <- ledger.activeContracts(party)
flatTransaction <- ledger.flatTransactionByEventId(dummyEvent.eventId, party)
transactionTree <- ledger.transactionTreeByEventId(dummyEvent.eventId, party)
@ -363,7 +362,10 @@ class ActiveContractsServiceIT extends LedgerTestSuite {
allocate(TwoParties),
)(implicit ec => { case Participants(Participant(ledger, alice, bob)) =>
for {
witnesses <- ledger.create(alice, TestWitnesses(alice, bob, bob))
witnesses: TestWitnesses.ContractId <- ledger.create(
alice,
new TestWitnesses(alice, bob, bob),
)
_ <- ledger.exercise(bob, witnesses.exerciseWitnessesCreateNewWitnesses())
bobContracts <- ledger.activeContracts(bob)
aliceContracts <- ledger.activeContracts(alice)
@ -385,8 +387,8 @@ class ActiveContractsServiceIT extends LedgerTestSuite {
allocate(TwoParties),
)(implicit ec => { case Participants(Participant(ledger, alice, bob)) =>
for {
divulgence1 <- ledger.create(alice, Divulgence1(alice))
divulgence2 <- ledger.create(bob, Divulgence2(bob, alice))
divulgence1 <- ledger.create(alice, new Divulgence1(alice))
divulgence2 <- ledger.create(bob, new Divulgence2(bob, alice))
_ <- ledger.exercise(alice, divulgence2.exerciseDivulgence2Fetch(divulgence1))
bobContracts <- ledger.activeContracts(bob)
aliceContracts <- ledger.activeContracts(alice)
@ -408,13 +410,13 @@ class ActiveContractsServiceIT extends LedgerTestSuite {
allocate(TwoParties),
)(implicit ec => { case Participants(Participant(ledger, alice, bob)) =>
for {
_ <- ledger.create(alice, WithObservers(alice, Seq(alice, bob)))
_ <- ledger.create(alice, new WithObservers(alice, Seq(alice, bob).map(_.getValue).asJava))
contracts <- ledger.activeContracts(alice)
} yield {
assert(contracts.nonEmpty)
contracts.foreach(ce =>
assert(
ce.observers == Seq(bob),
ce.observers == Seq(bob.getValue),
s"Expected observers to only contain $bob, but received ${ce.observers}",
)
)
@ -427,7 +429,7 @@ class ActiveContractsServiceIT extends LedgerTestSuite {
allocate(Parties(3)),
)(implicit ec => { case Participants(Participant(ledger, alice, bob, charlie)) =>
for {
_ <- ledger.create(alice, WithObservers(alice, List(bob, charlie)))
_ <- ledger.create(alice, new WithObservers(alice, List(bob, charlie).map(_.getValue).asJava))
bobContracts <- ledger.activeContracts(bob)
aliceBobContracts <- ledger.activeContracts(alice, bob)
bobCharlieContracts <- ledger.activeContracts(bob, charlie)
@ -438,7 +440,7 @@ class ActiveContractsServiceIT extends LedgerTestSuite {
s"Expected to receive 1 active contracts for $requesters, but received ${contracts.size}.",
)
assert(
contracts.head.witnessParties.toSet == requesters.map(_.toString),
contracts.head.witnessParties.toSet == requesters.map(_.getValue),
s"Expected witness parties to equal to $requesters, but received ${contracts.head.witnessParties}",
)
}
@ -456,7 +458,9 @@ class ActiveContractsServiceIT extends LedgerTestSuite {
)(implicit ec => { case Participants(Participant(ledger, p1, p2, p3)) =>
// Let us have 3 templates
val templateIds: Vector[Identifier] =
Vector(TriAgreement.id.unwrap, TriProposal.id.unwrap, WithObservers.id.unwrap)
Vector(TriAgreement.TEMPLATE_ID, TriProposal.TEMPLATE_ID, WithObservers.TEMPLATE_ID).map(t =>
Identifier.fromJavaProto(t.toProto)
)
// Let us have 3 parties
val parties: Vector[Party] = Vector(p1, p2, p3)
// Let us have all combinations for the 3 parties
@ -504,8 +508,10 @@ class ActiveContractsServiceIT extends LedgerTestSuite {
).map(filter => filter -> filterCoordsForFilter(filter))
def createContracts: Future[Map[FilterCoord, Set[String]]] = {
def withThreeParties[T](f: (Party, Party, Party) => T)(partySet: Set[Party]): T =
partySet.toList match {
def withThreeParties[T <: Template](
f: (String, String, String) => T
)(partySet: Set[Party]): T =
partySet.toList.map(_.getValue) match {
case a :: b :: c :: Nil => f(a, b, c)
case a :: b :: Nil => f(a, b, b)
case a :: Nil => f(a, a, a)
@ -513,19 +519,42 @@ class ActiveContractsServiceIT extends LedgerTestSuite {
throw new Exception(s"Invalid partySet, length must be 1 or 2 or 3 but it was $invalid")
}
val templateFactories: Vector[Set[Party] => Template[Template[Any]]] = Vector(
withThreeParties(TriAgreement(_, _, _)),
withThreeParties(TriProposal(_, _, _)),
parties => WithObservers(parties.head, parties.toList),
)
def createContractFor(template: Int, partyCombination: Int) =
ledger.create(
partyCombinations(partyCombination).map(parties).toList,
partyCombinations(partyCombination).map(parties).toList,
templateFactories(template)(partyCombinations(partyCombination).map(parties)),
val templateFactories: Vector[Set[Party] => _ <: Template] =
Vector(
(parties: Set[Party]) => withThreeParties(new TriAgreement(_, _, _))(parties),
(parties: Set[Party]) => withThreeParties(new TriProposal(_, _, _))(parties),
(parties: Set[Party]) =>
new WithObservers(parties.head, parties.toList.map(_.getValue).asJava),
)
def createContractFor(
template: Int,
partyCombination: Int,
): Future[ContractId[_]] = {
val partiesSet = partyCombinations(partyCombination).map(parties)
templateFactories(template)(partiesSet) match {
case agreement: TriAgreement =>
ledger.create(
partiesSet.toList,
partiesSet.toList,
agreement,
)(TriAgreement.COMPANION)
case proposal: TriProposal =>
ledger.create(
partiesSet.toList,
partiesSet.toList,
proposal,
)(TriProposal.COMPANION)
case withObservers: WithObservers =>
ledger.create(
partiesSet.toList,
partiesSet.toList,
withObservers,
)(WithObservers.COMPANION)
case t => throw new RuntimeException(s"the template given has an unexpected type $t")
}
}
val createFs = for {
partyCombinationIndex <- partyCombinations.indices
templateIndex <- templateFactories.indices
@ -538,7 +567,7 @@ class ActiveContractsServiceIT extends LedgerTestSuite {
.map(_.groupBy(_._1).map { case ((partyCombinationIndex, templateIndex), contractId) =>
(
FilterCoord(templateIndex, partyCombinations(partyCombinationIndex)),
contractId.view.map(_._2.toString).toSet,
contractId.view.map(_._2.contractId).toSet,
)
})
}
@ -558,10 +587,10 @@ class ActiveContractsServiceIT extends LedgerTestSuite {
new TransactionFilter(
filter.map {
case (party, templates) if templates.isEmpty =>
(parties(party).toString, new Filters(None))
(parties(party).getValue, new Filters(None))
case (party, templates) =>
(
parties(party).toString,
parties(party).getValue,
new Filters(
Some(
new InclusiveFilters(random.shuffle(templates.toSeq.map(templateIds)))
@ -631,11 +660,12 @@ class ActiveContractsServiceIT extends LedgerTestSuite {
partyAllocation = allocate(SingleParty),
runConcurrently = false,
)(implicit ec => { case Participants(Participant(ledger, party)) =>
val transactionFilter = Some(TransactionFilter(filtersByParty = Map(party.unwrap -> Filters())))
val transactionFilter =
Some(TransactionFilter(filtersByParty = Map(party.getValue -> Filters())))
for {
c1 <- ledger.create(party, Dummy(party))
c1 <- ledger.create(party, new Dummy(party))
offset1 <- ledger.currentEnd()
c2 <- ledger.create(party, Dummy(party))
c2 <- ledger.create(party, new Dummy(party))
offset2 <- ledger.currentEnd()
// acs at offset1
(acsOffset1, acs1) <- ledger
@ -679,15 +709,16 @@ class ActiveContractsServiceIT extends LedgerTestSuite {
partyAllocation = allocate(SingleParty),
runConcurrently = false,
)(implicit ec => { case Participants(Participant(ledger, party)) =>
val transactionFilter = Some(TransactionFilter(filtersByParty = Map(party.unwrap -> Filters())))
val transactionFilter =
Some(TransactionFilter(filtersByParty = Map(party.getValue -> Filters())))
for {
c1 <- ledger.create(party, Dummy(party))
c1 <- ledger.create(party, new Dummy(party))
anOffset <- ledger.currentEnd()
_ <- ledger.create(party, Dummy(party))
_ <- ledger.create(party, new Dummy(party))
_ <- ledger.pruneCantonSafe(
pruneUpTo = anOffset,
party = party,
dummyCommand = Dummy(_).create.command,
dummyCommand = p => new Dummy(p).create.commands,
)
(acsOffset, acs) <- ledger
.activeContractsIds(
@ -709,13 +740,18 @@ class ActiveContractsServiceIT extends LedgerTestSuite {
partyAllocation = allocate(SingleParty),
runConcurrently = false,
)(implicit ec => { case Participants(Participant(ledger, party)) =>
val transactionFilter = Some(TransactionFilter(filtersByParty = Map(party.unwrap -> Filters())))
val transactionFilter =
Some(TransactionFilter(filtersByParty = Map(party.getValue -> Filters())))
for {
offset1 <- ledger.currentEnd()
_ <- ledger.create(party, Dummy(party))
_ <- ledger.create(party, new Dummy(party))
offset2 <- ledger.currentEnd()
_ <- ledger.create(party, Dummy(party))
_ <- ledger.pruneCantonSafe(pruneUpTo = offset2, party = party, Dummy(_).create.command)
_ <- ledger.create(party, new Dummy(party))
_ <- ledger.pruneCantonSafe(
pruneUpTo = offset2,
party = party,
p => new Dummy(p).create.commands,
)
_ <- ledger
.activeContractsIds(
GetActiveContractsRequest(
@ -737,7 +773,8 @@ class ActiveContractsServiceIT extends LedgerTestSuite {
disabledReason = "Requires ACS with active_at_offset",
partyAllocation = allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
val transactionFilter = Some(TransactionFilter(filtersByParty = Map(party.unwrap -> Filters())))
val transactionFilter =
Some(TransactionFilter(filtersByParty = Map(party.getValue -> Filters())))
for {
_ <- ledger
.activeContracts(
@ -761,7 +798,8 @@ class ActiveContractsServiceIT extends LedgerTestSuite {
partyAllocation = allocate(SingleParty),
runConcurrently = false,
)(implicit ec => { case Participants(Participant(ledger, party)) =>
val transactionFilter = Some(TransactionFilter(filtersByParty = Map(party.unwrap -> Filters())))
val transactionFilter =
Some(TransactionFilter(filtersByParty = Map(party.getValue -> Filters())))
for {
offsetBeyondLedgerEnd <- ledger.offsetBeyondLedgerEnd()
_ <- ledger
@ -782,25 +820,26 @@ class ActiveContractsServiceIT extends LedgerTestSuite {
ec: ExecutionContext
): Future[
(
Primitive.ContractId[Dummy],
Primitive.ContractId[DummyWithParam],
Primitive.ContractId[DummyFactory],
Dummy.ContractId,
DummyWithParam.ContractId,
DummyFactory.ContractId,
)
] = {
for {
dummy <- ledger.create(party, Dummy(party))
dummyWithParam <- ledger.create(party, DummyWithParam(party))
dummyFactory <- ledger.create(party, DummyFactory(party))
dummy <- ledger.create(party, new Dummy(party))
dummyWithParam <- ledger.create(party, new DummyWithParam(party))
dummyFactory <- ledger.create(party, new DummyFactory(party))
} yield (dummy, dummyWithParam, dummyFactory)
}
private def assertTemplates[A](
private def assertTemplates(
party: Seq[Party],
events: Vector[CreatedEvent],
templateId: TemplateId[A],
templateId: JavaIdentifier,
count: Int,
): Unit = {
val templateEvents = events.count(_.getTemplateId == templateId.unwrap)
val templateEvents =
events.count(_.getTemplateId == Identifier.fromJavaProto(templateId.toProto))
assert(
templateEvents == count,
s"${party.mkString(" and ")} expected $count $templateId events, but received $templateEvents.",

View File

@ -9,12 +9,14 @@ import com.daml.error.definitions.LedgerApiErrors
import com.daml.ledger.api.testtool.infrastructure.Allocation._
import com.daml.ledger.api.testtool.infrastructure.Assertions._
import com.daml.ledger.api.testtool.infrastructure.LedgerTestSuite
import com.daml.ledger.client.binding
import com.daml.ledger.test.semantic.SemanticTests.{Amount, Iou}
import com.daml.ledger.test.java.semantic.semantictests.{Amount, Iou}
import java.math.BigDecimal
class ClosedWorldIT extends LedgerTestSuite {
import CompanionImplicits._
private[this] val onePound = Amount(BigDecimal(1), "GBP")
private[this] val onePound = new Amount(BigDecimal.valueOf(1), "GBP")
/*
* All informees in a transaction must be allocated.
@ -27,7 +29,7 @@ class ClosedWorldIT extends LedgerTestSuite {
)(implicit ec => { case Participants(Participant(alpha, payer)) =>
for {
failure <- alpha
.create(payer, Iou(payer, binding.Primitive.Party("unallocated"), onePound))
.create(payer, new Iou(payer, "unallocated", onePound))
.mustFail("referencing an unallocated party")
} yield {
assertGrpcErrorRegex(

View File

@ -4,7 +4,6 @@
package com.daml.ledger.api.testtool.suites.v1_8
import java.time
import com.daml.error.ErrorCode
import com.daml.error.definitions.LedgerApiErrors
import com.daml.grpc.GrpcStatus
@ -30,9 +29,9 @@ import com.daml.ledger.api.v1.completion.Completion.{
}
import com.daml.ledger.api.v1.experimental_features.CommandDeduplicationPeriodSupport.OffsetSupport
import com.daml.ledger.api.v1.ledger_offset.LedgerOffset
import com.daml.ledger.client.binding.Primitive.Party
import com.daml.ledger.test.model.DA.Types.Tuple2
import com.daml.ledger.test.model.Test.{Dummy, DummyWithAnnotation, TextKey, TextKeyOperations}
import com.daml.ledger.javaapi.data.Party
import com.daml.ledger.test.java.model.da.types.Tuple2
import com.daml.ledger.test.java.model.test.{Dummy, DummyWithAnnotation, TextKey, TextKeyOperations}
import com.daml.lf.data.Ref
import com.daml.lf.data.Ref.{LedgerString, SubmissionId}
import com.daml.logging.LoggingContext
@ -41,6 +40,7 @@ import org.slf4j.{Logger, LoggerFactory}
import scala.concurrent.duration._
import scala.concurrent.{ExecutionContext, Future}
import scala.jdk.CollectionConverters._
import scala.util.control.NonFatal
import scala.util.{Failure, Success}
@ -48,6 +48,8 @@ final class CommandDeduplicationIT(
timeoutScaleFactor: Double
) extends LedgerTestSuite {
import CompanionImplicits._
private[this] val logger: Logger = LoggerFactory.getLogger(getClass.getName)
private implicit val loggingContext: LoggingContext = LoggingContext.ForTesting
private val deduplicationDuration: FiniteDuration =
@ -59,7 +61,7 @@ final class CommandDeduplicationIT(
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
val request = ledger
.submitRequest(party, DummyWithAnnotation(party, "Duplicate command").create.command)
.submitRequest(party, new DummyWithAnnotation(party, "Duplicate command").create.commands)
.update(
_.commands.deduplicationPeriod :=
DeduplicationPeriod.DeduplicationDuration(deduplicationDuration.asProtobuf)
@ -102,7 +104,7 @@ final class CommandDeduplicationIT(
)(implicit ec => { case Participants(Participant(ledger, alice, bob)) =>
// Do not set the deduplication timeout.
// The server will default to the maximum possible deduplication timeout.
val requestA = ledger.submitRequest(alice, Dummy(bob).create.command)
val requestA = ledger.submitRequest(alice, new Dummy(bob).create.commands)
for {
// Submit an invalid command (should fail with INVALID_ARGUMENT)
@ -132,17 +134,17 @@ final class CommandDeduplicationIT(
for {
// Create a helper and a text key
ko <- ledger.create(party, TextKeyOperations(party))
_ <- ledger.create(party, TextKey(party, key, List()))
ko <- ledger.create(party, new TextKeyOperations(party))
_ <- ledger.create(party, new TextKey(party, key, List().asJava))
// Create two competing requests
requestA = ledger.submitAndWaitRequest(
party,
ko.exerciseTKOFetchAndRecreate(Tuple2(party, key)).command,
ko.exerciseTKOFetchAndRecreate(new Tuple2(party.getValue, key)).commands,
)
requestB = ledger.submitAndWaitRequest(
party,
ko.exerciseTKOFetchAndRecreate(Tuple2(party, key)).command,
ko.exerciseTKOFetchAndRecreate(new Tuple2(party.getValue, key)).commands,
)
// Submit both requests in parallel.
@ -170,7 +172,7 @@ final class CommandDeduplicationIT(
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
val request = ledger
.submitAndWaitRequest(party, Dummy(party).create.command)
.submitAndWaitRequest(party, new Dummy(party).create.commands)
.update(
_.commands.deduplicationTime := deduplicationDuration.asProtobuf
)
@ -251,12 +253,12 @@ final class CommandDeduplicationIT(
ec: ExecutionContext
) = {
val submitAndWaitRequest = ledger
.submitAndWaitRequest(party, Dummy(party).create.command)
.submitAndWaitRequest(party, new Dummy(party).create.commands)
.update(
_.commands.deduplicationTime := deduplicationDuration.asProtobuf
)
val submitRequest = ledger
.submitRequest(party, Dummy(party).create.command)
.submitRequest(party, new Dummy(party).create.commands)
.update(
_.commands.commandId := submitAndWaitRequest.getCommands.commandId,
_.commands.deduplicationTime := deduplicationDuration.asProtobuf,
@ -346,9 +348,9 @@ final class CommandDeduplicationIT(
"Commands with identical submitter and command identifier should be deduplicated by the submission client",
allocate(TwoParties),
)(implicit ec => { case Participants(Participant(ledger, alice, bob)) =>
val aliceRequest = ledger.submitRequest(alice, Dummy(alice).create.command)
val aliceRequest = ledger.submitRequest(alice, new Dummy(alice).create.commands)
val bobRequest = ledger
.submitRequest(bob, Dummy(bob).create.command)
.submitRequest(bob, new Dummy(bob).create.commands)
.update(_.commands.commandId := aliceRequest.getCommands.commandId)
val aliceAcceptedSubmissionId = newSubmissionId()
@ -400,9 +402,9 @@ final class CommandDeduplicationIT(
"Commands with identical submitter and command identifier should be deduplicated by the command client",
allocate(TwoParties),
)(implicit ec => { case Participants(Participant(ledger, alice, bob)) =>
val aliceRequest = ledger.submitAndWaitRequest(alice, Dummy(alice).create.command)
val aliceRequest = ledger.submitAndWaitRequest(alice, new Dummy(alice).create.commands)
val bobRequest = ledger
.submitAndWaitRequest(bob, Dummy(bob).create.command)
.submitAndWaitRequest(bob, new Dummy(bob).create.commands)
.update(_.commands.commandId := aliceRequest.getCommands.commandId)
val aliceAcceptedSubmissionId = newSubmissionId()
@ -457,7 +459,7 @@ final class CommandDeduplicationIT(
)(implicit ec =>
configuredParticipants => { case Participants(Participant(ledger, party)) =>
val request = ledger
.submitRequest(party, DummyWithAnnotation(party, "Duplicate command").create.command)
.submitRequest(party, new DummyWithAnnotation(party, "Duplicate command").create.commands)
.update(
_.commands.deduplicationPeriod :=
DeduplicationPeriod.DeduplicationDuration(deduplicationDuration.asProtobuf)
@ -532,12 +534,15 @@ final class CommandDeduplicationIT(
)(implicit ec =>
configuredParticipants => { case Participants(Participant(ledger, party)) =>
val request = ledger
.submitRequest(party, DummyWithAnnotation(party, "Duplicate command").create.command)
.submitRequest(party, new DummyWithAnnotation(party, "Duplicate command").create.commands)
val acceptedSubmissionId = newSubmissionId()
runWithTimeModel(configuredParticipants) { _ =>
val dummyRequest = ledger.submitRequest(
party,
DummyWithAnnotation(party, "Dummy command to generate a completion offset").create.command,
new DummyWithAnnotation(
party,
"Dummy command to generate a completion offset",
).create.commands,
)
for {
// Send a dummy command to the ledger so that we obtain a recent offset

View File

@ -4,7 +4,6 @@
package com.daml.ledger.api.testtool.suites.v1_8
import java.util.UUID
import com.daml.grpc.GrpcException
import com.daml.ledger.api.testtool.infrastructure.Allocation.{
Participant,
@ -19,11 +18,8 @@ import com.daml.ledger.api.testtool.infrastructure.participant.ParticipantTestCo
import com.daml.ledger.api.v1.command_service.SubmitAndWaitRequest
import com.daml.ledger.api.v1.command_submission_service.SubmitRequest
import com.daml.ledger.api.v1.commands.Commands.DeduplicationPeriod
import com.daml.ledger.client
import com.daml.ledger.client.binding
import com.daml.ledger.client.binding.Primitive
import com.daml.ledger.client.binding.Primitive.Party
import com.daml.ledger.test.model.Test.DummyWithAnnotation
import com.daml.ledger.javaapi.data.Party
import com.daml.ledger.test.java.model.test.DummyWithAnnotation
import io.grpc.Status
import io.grpc.Status.Code
@ -118,11 +114,11 @@ class CommandDeduplicationParallelIT extends LedgerTestSuite {
private def buildSubmitRequest(
ledger: ParticipantTestContext,
party: client.binding.Primitive.Party,
party: Party,
) = ledger
.submitRequest(
party,
DummyWithAnnotation(party, "Duplicate Using CommandSubmissionService").create.command,
new DummyWithAnnotation(party, "Duplicate Using CommandSubmissionService").create.commands,
)
.update(
_.commands.deduplicationPeriod := DeduplicationPeriod.DeduplicationDuration(
@ -132,11 +128,11 @@ class CommandDeduplicationParallelIT extends LedgerTestSuite {
private def buildSubmitAndWaitRequest(
ledger: ParticipantTestContext,
party: binding.Primitive.Party,
party: Party,
) = ledger
.submitAndWaitRequest(
party,
DummyWithAnnotation(party, "Duplicate using CommandService").create.command,
new DummyWithAnnotation(party, "Duplicate using CommandService").create.commands,
)
.update(
_.commands.deduplicationDuration := deduplicationDuration.asProtobuf
@ -163,7 +159,7 @@ class CommandDeduplicationParallelIT extends LedgerTestSuite {
private def submissionResultToFinalStatusCode(
ledger: ParticipantTestContext
)(submitResult: Future[Unit], submissionId: String, parties: Primitive.Party*)(implicit
)(submitResult: Future[Unit], submissionId: String, parties: Party*)(implicit
ec: ExecutionContext
) = submitResult
.transformWith {

View File

@ -5,18 +5,17 @@ package com.daml.ledger.api.testtool.suites.v1_8
import java.time.Duration
import java.util.regex.Pattern
import com.daml.api.util.DurationConversion
import com.daml.error.ErrorCode
import com.daml.error.definitions.LedgerApiErrors
import com.daml.ledger.api.testtool.infrastructure.Allocation._
import com.daml.ledger.api.testtool.infrastructure.Assertions._
import com.daml.ledger.api.testtool.infrastructure.assertions.CommandDeduplicationAssertions.DurationConversion
import com.daml.ledger.api.testtool.infrastructure.participant.ParticipantTestContext
import com.daml.ledger.api.testtool.infrastructure.{FutureAssertions, LedgerTestSuite}
import com.daml.ledger.api.v1.commands.Commands.DeduplicationPeriod
import com.daml.ledger.api.v1.ledger_offset.LedgerOffset
import com.daml.ledger.client.binding.Primitive
import com.daml.ledger.test.model.Test.Dummy
import com.daml.ledger.javaapi.data.Party
import com.daml.ledger.test.java.model.test.Dummy
import com.daml.lf.data.Ref
import com.daml.logging.LoggingContext
@ -24,6 +23,7 @@ import scala.concurrent.ExecutionContext
import scala.concurrent.duration._
class CommandDeduplicationPeriodValidationIT extends LedgerTestSuite {
import CompanionImplicits._
private implicit val loggingContext: LoggingContext = LoggingContext.ForTesting
@ -33,7 +33,7 @@ class CommandDeduplicationPeriodValidationIT extends LedgerTestSuite {
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
// Submission using the maximum allowed deduplication time
val request = ledger.submitRequest(party, Dummy(party).create.command)
val request = ledger.submitRequest(party, new Dummy(party).create.commands)
for {
config <- ledger.configuration()
maxDedupDuration = config.maxDeduplicationDuration.get
@ -88,7 +88,7 @@ class CommandDeduplicationPeriodValidationIT extends LedgerTestSuite {
enabled = _.commandDeduplicationFeatures.maxDeduplicationDurationEnforced,
disabledReason = "Maximum deduplication duration is not enforced by the ledger",
)(implicit ec => { case Participants(Participant(ledger, party)) =>
val request = ledger.submitRequest(party, Dummy(party).create.command)
val request = ledger.submitRequest(party, new Dummy(party).create.commands)
val expectedError = LedgerApiErrors.RequestValidation.InvalidDeduplicationPeriodField
for {
config <- ledger.configuration()
@ -163,7 +163,7 @@ class CommandDeduplicationPeriodValidationIT extends LedgerTestSuite {
ledger
.submitAndWait(
ledger
.submitAndWaitRequest(party, Dummy(party).create.command)
.submitAndWaitRequest(party, new Dummy(party).create.commands)
.update(
_.commands.deduplicationPeriod := deduplicationPeriod
)
@ -173,10 +173,12 @@ class CommandDeduplicationPeriodValidationIT extends LedgerTestSuite {
ledger.features.commandDeduplicationFeatures.getDeduplicationPeriodSupport.offsetSupport.isOffsetNativeSupport
for {
start <- ledger.currentEnd()
firstCreate <- ledger.create(party, Dummy(party))
firstCreate <- ledger.create(party, new Dummy(party))
_ <- ledger.exercise(party, firstCreate.exerciseDummyChoice1())
secondCreate <- ledger.create(party, Dummy(party))
_ <- ledger.submitAndWait(ledger.submitAndWaitRequest(party, Dummy(party).create.command))
secondCreate: Dummy.ContractId <- ledger.create(party, new Dummy(party))
_ <- ledger.submitAndWait(
ledger.submitAndWaitRequest(party, new Dummy(party).create.commands)
)
end <- ledger.currentEnd()
_ <- ledger.exercise(party, secondCreate.exerciseDummyChoice1())
_ <- FutureAssertions.succeedsEventually(
@ -186,8 +188,10 @@ class CommandDeduplicationPeriodValidationIT extends LedgerTestSuite {
"Prune offsets",
) {
for {
_ <- ledger.create(party, Dummy(party))
_ <- ledger.submitAndWait(ledger.submitAndWaitRequest(party, Dummy(party).create.command))
_ <- ledger.create(party, new Dummy(party))
_ <- ledger.submitAndWait(
ledger.submitAndWaitRequest(party, new Dummy(party).create.commands)
)
_ <- ledger.prune(pruneUpTo = end, attempts = 1)
} yield {}
}
@ -226,7 +230,7 @@ class CommandDeduplicationPeriodValidationIT extends LedgerTestSuite {
})
private def findFirstOffsetAfterGivenOffset(ledger: ParticipantTestContext, offset: String)(
party: Primitive.Party
party: Party
)(implicit ec: ExecutionContext) = {
ledger
.findCompletion(
@ -244,7 +248,7 @@ class CommandDeduplicationPeriodValidationIT extends LedgerTestSuite {
private def assertSyncFailedRequest(
ledger: ParticipantTestContext,
party: Primitive.Party,
party: Party,
deduplicationPeriod: DeduplicationPeriod,
failReason: String,
expectedMessage: String,
@ -254,7 +258,7 @@ class CommandDeduplicationPeriodValidationIT extends LedgerTestSuite {
failure <- ledger
.submit(
ledger
.submitRequest(party, Dummy(party).create.command)
.submitRequest(party, new Dummy(party).create.commands)
.update(
_.commands.deduplicationPeriod := deduplicationPeriod
)

View File

@ -4,24 +4,21 @@
package com.daml.ledger.api.testtool.suites.v1_8
import java.util.regex.Pattern
import com.daml.error.definitions.LedgerApiErrors
import com.daml.ledger.api.testtool.infrastructure.Allocation._
import com.daml.ledger.api.testtool.infrastructure.Assertions._
import com.daml.ledger.api.testtool.infrastructure.LedgerTestSuite
import com.daml.ledger.api.testtool.infrastructure.Synchronize.synchronize
import com.daml.ledger.javaapi.data.Command
import com.daml.ledger.api.testtool.infrastructure.TransactionHelpers._
import com.daml.ledger.api.v1.command_service.SubmitAndWaitForTransactionResponse
import com.daml.ledger.api.v1.commands.Command
import com.daml.ledger.api.v1.value.{Record, RecordField, Value}
import com.daml.ledger.client.binding.Primitive
import com.daml.ledger.client.binding.Value.encode
import com.daml.ledger.test.model.Test.CallablePayout._
import com.daml.ledger.test.model.Test.Dummy._
import com.daml.ledger.test.model.Test.DummyFactory._
import com.daml.ledger.test.model.Test.WithObservers._
import com.daml.ledger.test.model.Test._
import scalaz.syntax.tag._
import com.daml.ledger.test.java.model.test._
import CompanionImplicits._
import java.math.BigDecimal
import java.util.{List => JList}
import scala.jdk.CollectionConverters._
final class CommandServiceIT extends LedgerTestSuite {
test(
@ -29,14 +26,14 @@ final class CommandServiceIT extends LedgerTestSuite {
"SubmitAndWait creates a contract of the expected template",
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
val request = ledger.submitAndWaitRequest(party, Dummy(party).create.command)
val request = ledger.submitAndWaitRequest(party, new Dummy(party).create.commands)
for {
_ <- ledger.submitAndWait(request)
active <- ledger.activeContracts(party)
} yield {
assert(active.size == 1)
val dummyTemplateId = active.flatMap(_.templateId.toList).head
assert(dummyTemplateId == Dummy.id.unwrap)
assert(dummyTemplateId == Dummy.TEMPLATE_ID.toV1)
}
})
@ -45,7 +42,7 @@ final class CommandServiceIT extends LedgerTestSuite {
"SubmitAndWaitForTransactionId returns a valid transaction identifier",
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
val request = ledger.submitAndWaitRequest(party, Dummy(party).create.command)
val request = ledger.submitAndWaitRequest(party, new Dummy(party).create.commands)
for {
transactionIdResponse <- ledger.submitAndWaitForTransactionId(request)
transactionId = transactionIdResponse.transactionId
@ -95,7 +92,7 @@ final class CommandServiceIT extends LedgerTestSuite {
"SubmitAndWaitForTransaction returns a transaction",
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
val request = ledger.submitAndWaitRequest(party, Dummy(party).create.command)
val request = ledger.submitAndWaitRequest(party, new Dummy(party).create.commands)
for {
transactionResponse <- ledger.submitAndWaitForTransaction(request)
} yield {
@ -111,7 +108,7 @@ final class CommandServiceIT extends LedgerTestSuite {
disabledReason = "Optional ledger id must be enabled",
)(implicit ec => { case Participants(Participant(ledger, party)) =>
val request = ledger
.submitAndWaitRequest(party, Dummy(party).create.command)
.submitAndWaitRequest(party, new Dummy(party).create.commands)
.update(_.commands.ledgerId := "")
for {
transactionResponse <- ledger
@ -135,8 +132,8 @@ final class CommandServiceIT extends LedgerTestSuite {
s"The returned transaction should contain a created-event, but was ${event.event}",
)
assert(
event.getCreated.getTemplateId == Dummy.id.unwrap,
s"The template ID of the created-event should by ${Dummy.id.unwrap}, but was ${event.getCreated.getTemplateId}",
event.getCreated.getTemplateId == Dummy.TEMPLATE_ID.toV1,
s"The template ID of the created-event should by ${Dummy.TEMPLATE_ID.toV1}, but was ${event.getCreated.getTemplateId}",
)
}
@ -145,7 +142,7 @@ final class CommandServiceIT extends LedgerTestSuite {
"SubmitAndWaitForTransactionTree returns a transaction tree",
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
val request = ledger.submitAndWaitRequest(party, Dummy(party).create.command)
val request = ledger.submitAndWaitRequest(party, new Dummy(party).create.commands)
for {
transactionTreeResponse <- ledger.submitAndWaitForTransactionTree(request)
} yield {
@ -164,8 +161,8 @@ final class CommandServiceIT extends LedgerTestSuite {
s"The returned transaction tree should contain a created-event, but was ${event.kind}",
)
assert(
event.getCreated.getTemplateId == Dummy.id.unwrap,
s"The template ID of the created-event should by ${Dummy.id.unwrap}, but was ${event.getCreated.getTemplateId}",
event.getCreated.getTemplateId == Dummy.TEMPLATE_ID.toV1,
s"The template ID of the created-event should by ${Dummy.TEMPLATE_ID.toV1}, but was ${event.getCreated.getTemplateId}",
)
}
})
@ -175,7 +172,7 @@ final class CommandServiceIT extends LedgerTestSuite {
"SubmitAndWait should fail on duplicate requests",
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
val request = ledger.submitAndWaitRequest(party, Dummy(party).create.command)
val request = ledger.submitAndWaitRequest(party, new Dummy(party).create.commands)
for {
_ <- ledger.submitAndWait(request)
failure <- ledger
@ -199,7 +196,7 @@ final class CommandServiceIT extends LedgerTestSuite {
"SubmitAndWaitForTransactionId should fail on duplicate requests",
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
val request = ledger.submitAndWaitRequest(party, Dummy(party).create.command)
val request = ledger.submitAndWaitRequest(party, new Dummy(party).create.commands)
for {
_ <- ledger.submitAndWaitForTransactionId(request)
failure <- ledger
@ -223,7 +220,7 @@ final class CommandServiceIT extends LedgerTestSuite {
"SubmitAndWaitForTransaction should fail on duplicate requests",
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
val request = ledger.submitAndWaitRequest(party, Dummy(party).create.command)
val request = ledger.submitAndWaitRequest(party, new Dummy(party).create.commands)
for {
_ <- ledger.submitAndWaitForTransaction(request)
failure <- ledger
@ -247,7 +244,7 @@ final class CommandServiceIT extends LedgerTestSuite {
"SubmitAndWaitForTransactionTree should fail on duplicate requests",
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
val request = ledger.submitAndWaitRequest(party, Dummy(party).create.command)
val request = ledger.submitAndWaitRequest(party, new Dummy(party).create.commands)
for {
_ <- ledger.submitAndWaitForTransactionTree(request)
failure <- ledger
@ -273,7 +270,7 @@ final class CommandServiceIT extends LedgerTestSuite {
)(implicit ec => { case Participants(Participant(ledger, party)) =>
val invalidLedgerId = "CSsubmitAndWaitForTransactionIdInvalidLedgerId"
val request = ledger
.submitAndWaitRequest(party, Dummy(party).create.command)
.submitAndWaitRequest(party, new Dummy(party).create.commands)
.update(_.commands.ledgerId := invalidLedgerId)
for {
failure <- ledger
@ -294,7 +291,7 @@ final class CommandServiceIT extends LedgerTestSuite {
)(implicit ec => { case Participants(Participant(ledger, party)) =>
val invalidLedgerId = "CSsubmitAndWaitForTransactionInvalidLedgerId"
val request = ledger
.submitAndWaitRequest(party, Dummy(party).create.command)
.submitAndWaitRequest(party, new Dummy(party).create.commands)
.update(_.commands.ledgerId := invalidLedgerId)
for {
failure <- ledger
@ -315,7 +312,7 @@ final class CommandServiceIT extends LedgerTestSuite {
)(implicit ec => { case Participants(Participant(ledger, party)) =>
val invalidLedgerId = "CSsubmitAndWaitForTransactionTreeInvalidLedgerId"
val request = ledger
.submitAndWaitRequest(party, Dummy(party).create.command)
.submitAndWaitRequest(party, new Dummy(party).create.commands)
.update(_.commands.ledgerId := invalidLedgerId)
for {
failure <- ledger
@ -334,8 +331,11 @@ final class CommandServiceIT extends LedgerTestSuite {
"The submission of a creation that contains a bad parameter label should result in an INVALID_ARGUMENT",
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
val createWithBadArgument = Dummy(party).create.command
.update(_.create.createArguments.fields.foreach(_.label := "INVALID_PARAM"))
val createWithBadArgument =
updateCommands(
new Dummy(party).create.commands,
_.update(_.create.createArguments.fields.foreach(_.label := "INVALID_PARAM")),
)
val badRequest = ledger.submitAndWaitRequest(party, createWithBadArgument)
for {
failure <- ledger
@ -360,7 +360,7 @@ final class CommandServiceIT extends LedgerTestSuite {
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
for {
dummy <- ledger.create(party, Dummy(party))
dummy: Dummy.ContractId <- ledger.create(party, new Dummy(party))
failure <- ledger
.exercise(party, dummy.exerciseFailingClone())
.mustFail("submitting a request with an interpretation error")
@ -384,7 +384,7 @@ final class CommandServiceIT extends LedgerTestSuite {
allocate(TwoParties, SingleParty),
)(implicit ec => {
case Participants(Participant(alpha, giver, observer1), Participant(beta, observer2)) =>
val template = WithObservers(giver, Primitive.List(observer1, observer2))
val template = new WithObservers(giver, List(observer1, observer2).map(_.getValue).asJava)
for {
_ <- alpha.create(giver, template)
_ <- synchronize(alpha, beta)
@ -407,7 +407,7 @@ final class CommandServiceIT extends LedgerTestSuite {
assertEquals(
"The observers should see the created contract",
observer1Created.getCreateArguments.fields,
encode(template).getRecord.fields,
Value.fromJavaProto(template.toValue.toProto).getRecord.fields,
)
}
})
@ -418,9 +418,9 @@ final class CommandServiceIT extends LedgerTestSuite {
allocate(TwoParties, SingleParty),
)(implicit ec => {
case Participants(Participant(alpha, giver, observer1), Participant(beta, observer2)) =>
val template = WithObservers(giver, Primitive.List(observer1, observer2))
val template = new WithObservers(giver, List(observer1, observer2).map(_.getValue).asJava)
for {
withObservers <- alpha.create(giver, template)
withObservers: WithObservers.ContractId <- alpha.create(giver, template)
_ <- alpha.exercise(giver, withObservers.exercisePing())
_ <- synchronize(alpha, beta)
observer1View <- alpha.transactionTrees(observer1)
@ -439,7 +439,7 @@ final class CommandServiceIT extends LedgerTestSuite {
"The two observers should see the same exercise",
)
assert(
observer1Exercise.contractId == withObservers.unwrap,
observer1Exercise.contractId == withObservers.contractId,
"The observers shouls see the exercised contract",
)
}
@ -451,8 +451,8 @@ final class CommandServiceIT extends LedgerTestSuite {
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
val target = 15
val commands = Vector.fill(target)(Dummy(party).create.command)
val request = ledger.submitAndWaitRequest(party, commands: _*)
val commands = List.fill(target)(new Dummy(party).create.commands.asScala).flatten
val request = ledger.submitAndWaitRequest(party, commands.asJava)
for {
_ <- ledger.submitAndWait(request)
acs <- ledger.activeContracts(party)
@ -471,7 +471,10 @@ final class CommandServiceIT extends LedgerTestSuite {
)(implicit ec => {
case Participants(Participant(alpha, giver, newReceiver), Participant(beta, receiver)) =>
for {
callablePayout <- alpha.create(giver, CallablePayout(giver, receiver))
callablePayout: CallablePayout.ContractId <- alpha.create(
giver,
new CallablePayout(giver, receiver),
)
_ <- synchronize(alpha, beta)
tree <- beta.exercise(receiver, callablePayout.exerciseTransfer(newReceiver))
} yield {
@ -479,7 +482,10 @@ final class CommandServiceIT extends LedgerTestSuite {
assertEquals(
"The created event should be the expected one",
created.getCreateArguments.fields,
encode(CallablePayout(giver, newReceiver)).getRecord.fields,
Value
.fromJavaProto(new CallablePayout(giver, newReceiver).toValue.toProto)
.getRecord
.fields,
)
}
})
@ -490,11 +496,11 @@ final class CommandServiceIT extends LedgerTestSuite {
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
for {
factory <- ledger.create(party, DummyFactory(party))
factory: DummyFactory.ContractId <- ledger.create(party, new DummyFactory(party))
tree <- ledger.exercise(party, factory.exerciseDummyFactoryCall())
} yield {
val exercise = assertSingleton("There should only be one exercise", exercisedEvents(tree))
assert(exercise.contractId == factory.unwrap, "Contract identifier mismatch")
assert(exercise.contractId == factory.contractId, "Contract identifier mismatch")
assert(exercise.consuming, "The choice should have been consuming")
val _ = assertLength("Two creations should have occurred", 2, createdEvents(tree))
}
@ -503,10 +509,13 @@ final class CommandServiceIT extends LedgerTestSuite {
test("CSBadNumericValues", "Reject unrepresentable numeric values", allocate(SingleParty))(
implicit ec => { case Participants(Participant(ledger, party)) =>
// Code generation catches bad decimals early so we have to do some work to create (possibly) invalid requests
def rounding(numeric: String): Command =
DecimalRounding(party, BigDecimal("0")).create.command.update(
_.create.createArguments
.fields(1) := RecordField(value = Some(Value(Value.Sum.Numeric(numeric))))
def rounding(numeric: String): JList[Command] =
updateCommands(
new DecimalRounding(party, BigDecimal.valueOf(0)).create.commands,
_.update(
_.create.createArguments
.fields(1) := RecordField(value = Some(Value(Value.Sum.Numeric(numeric))))
),
)
val wouldLosePrecision = "0.00000000005"
val positiveOutOfBounds = "10000000000000000000000000000.0000000000"
@ -546,7 +555,7 @@ final class CommandServiceIT extends LedgerTestSuite {
test("CSCreateAndExercise", "Implement create-and-exercise correctly", allocate(SingleParty))(
implicit ec => { case Participants(Participant(ledger, party)) =>
val createAndExercise = Dummy(party).createAnd.exerciseDummyChoice1().command
val createAndExercise = new Dummy(party).createAnd.exerciseDummyChoice1().commands
val request = ledger.submitAndWaitRequest(party, createAndExercise)
for {
_ <- ledger.submitAndWait(request)
@ -560,7 +569,7 @@ final class CommandServiceIT extends LedgerTestSuite {
assertEquals(
"Unexpected template identifier in create event",
trees.flatMap(createdEvents).map(_.getTemplateId),
Vector(Dummy.id.unwrap),
Vector(Dummy.TEMPLATE_ID.toV1),
)
val contractId = trees.flatMap(createdEvents).head.contractId
assertEquals(
@ -577,10 +586,13 @@ final class CommandServiceIT extends LedgerTestSuite {
"Fail create-and-exercise on bad create arguments",
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
val createAndExercise = Dummy(party).createAnd
.exerciseDummyChoice1()
.command
.update(_.createAndExercise.createArguments := Record())
val createAndExercise =
updateCommands(
new Dummy(party).createAnd
.exerciseDummyChoice1()
.commands,
_.update(_.createAndExercise.createArguments := Record()),
)
val request = ledger.submitAndWaitRequest(party, createAndExercise)
for {
failure <- ledger
@ -601,10 +613,13 @@ final class CommandServiceIT extends LedgerTestSuite {
"Fail create-and-exercise on bad choice arguments",
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
val createAndExercise = Dummy(party).createAnd
.exerciseDummyChoice1()
.command
.update(_.createAndExercise.choiceArgument := Value(Value.Sum.Bool(false)))
val createAndExercise =
updateCommands(
new Dummy(party).createAnd
.exerciseDummyChoice1()
.commands,
_.update(_.createAndExercise.choiceArgument := Value(Value.Sum.Bool(false))),
)
val request = ledger.submitAndWaitRequest(party, createAndExercise)
for {
failure <- ledger
@ -626,10 +641,13 @@ final class CommandServiceIT extends LedgerTestSuite {
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
val missingChoice = "DoesNotExist"
val createAndExercise = Dummy(party).createAnd
.exerciseDummyChoice1()
.command
.update(_.createAndExercise.choice := missingChoice)
val createAndExercise =
updateCommands(
new Dummy(party).createAnd
.exerciseDummyChoice1()
.commands,
_.update(_.createAndExercise.choice := missingChoice),
)
val request = ledger.submitAndWaitRequest(party, createAndExercise)
for {
failure <- ledger
@ -654,7 +672,7 @@ final class CommandServiceIT extends LedgerTestSuite {
"SubmitAndWait methods return the completion offset in the response",
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
def request = ledger.submitAndWaitRequest(party, Dummy(party).create.command)
def request = ledger.submitAndWaitRequest(party, new Dummy(party).create.commands)
for {
transactionIdResponse <- ledger.submitAndWaitForTransactionId(request)
retrievedTransaction <- ledger.transactionTreeById(transactionIdResponse.transactionId, party)

View File

@ -9,19 +9,19 @@ import com.daml.error.definitions.LedgerApiErrors
import com.daml.ledger.api.testtool.infrastructure.Allocation._
import com.daml.ledger.api.testtool.infrastructure.Assertions._
import com.daml.ledger.api.testtool.infrastructure.{LedgerTestSuite, TimeoutException, WithTimeout}
import com.daml.ledger.test.model.Test.Dummy
import com.daml.ledger.test.model.Test.Dummy._
import com.daml.ledger.test.java.model.test.Dummy
import scala.concurrent.duration.DurationInt
final class CommandSubmissionCompletionIT extends LedgerTestSuite {
import CompanionImplicits._
test(
"CSCCompletions",
"Read completions correctly with a correct application identifier and reading party",
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
val request = ledger.submitRequest(party, Dummy(party).create.command)
val request = ledger.submitRequest(party, new Dummy(party).create.commands)
for {
_ <- ledger.submit(request)
completions <- ledger.firstCompletions(party)
@ -40,7 +40,7 @@ final class CommandSubmissionCompletionIT extends LedgerTestSuite {
"Read no completions without the correct application identifier",
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
val request = ledger.submitRequest(party, Dummy(party).create.command)
val request = ledger.submitRequest(party, new Dummy(party).create.commands)
for {
_ <- ledger.submit(request)
invalidRequest = ledger
@ -58,7 +58,7 @@ final class CommandSubmissionCompletionIT extends LedgerTestSuite {
"An OUT_OF_RANGE error should be returned when subscribing to completions past the ledger end",
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
val request = ledger.submitRequest(party, Dummy(party).create.command)
val request = ledger.submitRequest(party, new Dummy(party).create.commands)
for {
_ <- ledger.submit(request)
futureOffset <- ledger.offsetBeyondLedgerEnd()
@ -82,7 +82,7 @@ final class CommandSubmissionCompletionIT extends LedgerTestSuite {
"Read no completions without the correct party",
allocate(TwoParties),
)(implicit ec => { case Participants(Participant(ledger, party, notTheSubmittingParty)) =>
val request = ledger.submitRequest(party, Dummy(party).create.command)
val request = ledger.submitRequest(party, new Dummy(party).create.commands)
for {
_ <- ledger.submit(request)
failure <- WithTimeout(5.seconds)(ledger.firstCompletions(notTheSubmittingParty))
@ -99,9 +99,9 @@ final class CommandSubmissionCompletionIT extends LedgerTestSuite {
)(implicit ec => { case Participants(Participant(ledger, party)) =>
val badChoice = "THIS_IS_NOT_A_VALID_CHOICE"
for {
dummy <- ledger.create(party, Dummy(party))
exercise = dummy.exerciseDummyChoice1().command
wrongExercise = exercise.update(_.exercise.choice := badChoice)
dummy <- ledger.create(party, new Dummy(party))
exercise = dummy.exerciseDummyChoice1().commands
wrongExercise = updateCommands(exercise, _.update(_.exercise.choice := badChoice))
wrongRequest = ledger.submitRequest(party, wrongExercise)
failure <- ledger.submit(wrongRequest).mustFail("submitting an invalid choice")
} yield {
@ -125,7 +125,7 @@ final class CommandSubmissionCompletionIT extends LedgerTestSuite {
)(implicit ec => { case Participants(Participant(ledger, party)) =>
val invalidLedgerId = "CSsubmitAndWaitInvalidLedgerId"
val request = ledger
.submitRequest(party, Dummy(party).create.command)
.submitRequest(party, new Dummy(party).create.commands)
.update(_.commands.ledgerId := invalidLedgerId)
for {
failure <- ledger.submit(request).mustFail("submitting with an invalid ledger ID")
@ -160,8 +160,8 @@ final class CommandSubmissionCompletionIT extends LedgerTestSuite {
"Listening for completions should support multi-party subscriptions",
allocate(TwoParties),
)(implicit ec => { case Participants(Participant(ledger, alice, bob)) =>
val aliceRequest = ledger.submitRequest(alice, Dummy(alice).create.command)
val bobRequest = ledger.submitRequest(bob, Dummy(bob).create.command)
val aliceRequest = ledger.submitRequest(alice, new Dummy(alice).create.commands)
val bobRequest = ledger.submitRequest(bob, new Dummy(bob).create.commands)
val aliceCommandId = aliceRequest.getCommands.commandId
val bobCommandId = bobRequest.getCommands.commandId
for {

View File

@ -0,0 +1,122 @@
// Copyright (c) 2023 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package com.daml.ledger.api.testtool.suites.v1_8
import com.daml.ledger.javaapi.data.codegen.ContractCompanion
import com.daml.ledger.test.java.model.da.types
import com.daml.ledger.test.java.model.iou.Iou
import com.daml.ledger.test.java.model.test
import com.daml.ledger.test.java.model.test.{
Agreement,
AgreementFactory,
CallablePayout,
Delegated,
Delegation,
Divulgence1,
Divulgence2,
Dummy,
DummyFactory,
DummyWithParam,
LocalKeyVisibilityOperations,
MaintainerNotSignatory,
ShowDelegated,
TextKey,
TextKeyOperations,
WithObservers,
Witnesses => TestWitnesses,
}
import com.daml.ledger.test.java.semantic.semantictests
object CompanionImplicits {
implicit val dummyCompanion
: ContractCompanion.WithoutKey[Dummy.Contract, Dummy.ContractId, Dummy] = Dummy.COMPANION
implicit val dummyWithParamCompanion: ContractCompanion.WithoutKey[
DummyWithParam.Contract,
DummyWithParam.ContractId,
DummyWithParam,
] = DummyWithParam.COMPANION
implicit val dummyFactoryCompanion
: ContractCompanion.WithoutKey[DummyFactory.Contract, DummyFactory.ContractId, DummyFactory] =
DummyFactory.COMPANION
implicit val withObserversCompanion: ContractCompanion.WithoutKey[
WithObservers.Contract,
WithObservers.ContractId,
WithObservers,
] = WithObservers.COMPANION
implicit val textKeyCompanion: ContractCompanion.WithKey[
TextKey.Contract,
TextKey.ContractId,
TextKey,
types.Tuple2[String, String],
] = TextKey.COMPANION
implicit val textKeyOperationsCompanion: ContractCompanion.WithoutKey[
TextKeyOperations.Contract,
TextKeyOperations.ContractId,
TextKeyOperations,
] = TextKeyOperations.COMPANION
implicit val callablePayoutCompanion: ContractCompanion.WithoutKey[
CallablePayout.Contract,
CallablePayout.ContractId,
CallablePayout,
] = CallablePayout.COMPANION
implicit val delegatedCompanion: ContractCompanion.WithKey[
Delegated.Contract,
Delegated.ContractId,
Delegated,
types.Tuple2[String, String],
] = Delegated.COMPANION
implicit val delegationCompanion
: ContractCompanion.WithoutKey[Delegation.Contract, Delegation.ContractId, Delegation] =
Delegation.COMPANION
implicit val showDelegatedCompanion: ContractCompanion.WithoutKey[
ShowDelegated.Contract,
ShowDelegated.ContractId,
ShowDelegated,
] = ShowDelegated.COMPANION
implicit val maintainerNotSignatoryCompanion: ContractCompanion.WithKey[
MaintainerNotSignatory.Contract,
MaintainerNotSignatory.ContractId,
MaintainerNotSignatory,
String,
] = MaintainerNotSignatory.COMPANION
implicit val testWitnessesCompanion: ContractCompanion.WithoutKey[
TestWitnesses.Contract,
TestWitnesses.ContractId,
TestWitnesses,
] = TestWitnesses.COMPANION
implicit val divulgence1Companion
: ContractCompanion.WithoutKey[Divulgence1.Contract, Divulgence1.ContractId, Divulgence1] =
Divulgence1.COMPANION
implicit val divulgence2Companion
: ContractCompanion.WithoutKey[Divulgence2.Contract, Divulgence2.ContractId, Divulgence2] =
Divulgence2.COMPANION
implicit val localKeyVisibilityOperationsCompanion: ContractCompanion.WithoutKey[
LocalKeyVisibilityOperations.Contract,
LocalKeyVisibilityOperations.ContractId,
LocalKeyVisibilityOperations,
] = LocalKeyVisibilityOperations.COMPANION
implicit val withKeyCompanion: ContractCompanion.WithKey[
test.WithKey.Contract,
test.WithKey.ContractId,
test.WithKey,
String,
] = test.WithKey.COMPANION
implicit val semanticTestsIouCompanion: ContractCompanion.WithoutKey[
semantictests.Iou.Contract,
semantictests.Iou.ContractId,
semantictests.Iou,
] = semantictests.Iou.COMPANION
implicit val iouCompanion: ContractCompanion.WithoutKey[Iou.Contract, Iou.ContractId, Iou] =
Iou.COMPANION
implicit val agreementFactoryCompanion: ContractCompanion.WithoutKey[
AgreementFactory.Contract,
AgreementFactory.ContractId,
AgreementFactory,
] = AgreementFactory.COMPANION
implicit val agreementCompanion
: ContractCompanion.WithoutKey[Agreement.Contract, Agreement.ContractId, Agreement] =
Agreement.COMPANION
}

View File

@ -11,16 +11,15 @@ import com.daml.ledger.api.testtool.infrastructure.participant.ParticipantTestCo
import com.daml.ledger.api.testtool.suites.v1_8.CompletionDeduplicationInfoIT._
import com.daml.ledger.api.v1.command_service.SubmitAndWaitRequest
import com.daml.ledger.api.v1.command_submission_service.SubmitRequest
import com.daml.ledger.api.v1.commands.Command
import com.daml.ledger.api.v1.completion.Completion
import com.daml.ledger.api.v1.ledger_offset.LedgerOffset
import com.daml.ledger.client.binding
import com.daml.ledger.client.binding.Primitive
import com.daml.ledger.test.model.Test.Dummy
import com.daml.ledger.javaapi.data.{Command, Party}
import com.daml.ledger.test.java.model.test.Dummy
import com.daml.lf.data.Ref
import com.daml.lf.data.Ref.SubmissionId
import io.grpc.Status
import java.util.{List => JList}
import scala.concurrent.duration.DurationInt
import scala.concurrent.{ExecutionContext, Future}
@ -61,13 +60,13 @@ private[testtool] object CompletionDeduplicationInfoIT {
private[testtool] sealed trait Service[ProtoRequestType] extends Serializable with Product {
def buildRequest(
ledger: ParticipantTestContext,
party: Primitive.Party,
party: Party,
optSubmissionId: Option[Ref.SubmissionId] = None,
): ProtoRequestType
def submitRequest(
ledger: ParticipantTestContext,
party: Primitive.Party,
party: Party,
request: ProtoRequestType,
)(implicit ec: ExecutionContext): Future[Option[Completion]]
@ -77,7 +76,7 @@ private[testtool] object CompletionDeduplicationInfoIT {
case object CommandService extends Service[SubmitAndWaitRequest] {
override def buildRequest(
ledger: ParticipantTestContext,
party: binding.Primitive.Party,
party: Party,
optSubmissionId: Option[SubmissionId],
): SubmitAndWaitRequest = {
val request = ledger.submitAndWaitRequest(party, simpleCreate(party))
@ -90,7 +89,7 @@ private[testtool] object CompletionDeduplicationInfoIT {
override def submitRequest(
ledger: ParticipantTestContext,
party: binding.Primitive.Party,
party: Party,
request: SubmitAndWaitRequest,
)(implicit ec: ExecutionContext): Future[Option[Completion]] =
for {
@ -112,7 +111,7 @@ private[testtool] object CompletionDeduplicationInfoIT {
case object CommandSubmissionService extends Service[SubmitRequest] {
override def buildRequest(
ledger: ParticipantTestContext,
party: binding.Primitive.Party,
party: Party,
optSubmissionId: Option[SubmissionId],
): SubmitRequest = {
val request = ledger.submitRequest(party, simpleCreate(party))
@ -125,7 +124,7 @@ private[testtool] object CompletionDeduplicationInfoIT {
override def submitRequest(
ledger: ParticipantTestContext,
party: binding.Primitive.Party,
party: Party,
request: SubmitRequest,
)(implicit ec: ExecutionContext): Future[Option[Completion]] =
for {
@ -142,7 +141,7 @@ private[testtool] object CompletionDeduplicationInfoIT {
private def singleCompletionAfterOffset(
ledger: ParticipantTestContext,
party: binding.Primitive.Party,
party: Party,
offset: LedgerOffset,
)(implicit ec: ExecutionContext): Future[Option[Completion]] =
WithTimeout(5.seconds)(
@ -189,7 +188,7 @@ private[testtool] object CompletionDeduplicationInfoIT {
)
}
private def simpleCreate(party: Primitive.Party): Command = Dummy(party).create.command
private def simpleCreate(party: Party): JList[Command] = new Dummy(party.getValue).create.commands
private val RandomSubmissionId =
Ref.SubmissionId.assertFromString(SubmissionIdGenerator.Random.generate())

View File

@ -5,19 +5,18 @@ package com.daml.ledger.api.testtool.suites.v1_8
import com.daml.error.ErrorCode
import com.daml.error.definitions.LedgerApiErrors
import com.daml.ledger.api.refinements.ApiTypes.Party
import com.daml.ledger.api.testtool.infrastructure.Allocation._
import com.daml.ledger.api.testtool.infrastructure.Assertions.{
assertGrpcError,
assertErrorCode,
assertGrpcError,
fail,
}
import com.daml.ledger.api.testtool.infrastructure.LedgerTestSuite
import com.daml.ledger.api.testtool.infrastructure.participant.{Features, ParticipantTestContext}
import com.daml.ledger.api.testtool.suites.v1_8.ContractIdIT._
import com.daml.ledger.api.v1.value.{Record, RecordField, Value}
import com.daml.ledger.client.binding.Primitive.ContractId
import com.daml.ledger.test.semantic.ContractIdTests._
import com.daml.ledger.javaapi.data.{ContractId, DamlRecord, Party}
import com.daml.ledger.javaapi.data.codegen.ContractCompanion
import com.daml.ledger.test.java.semantic.contractidtests._
import io.grpc.StatusRuntimeException
import scala.concurrent.{ExecutionContext, Future}
@ -28,6 +27,16 @@ import scala.util.{Failure, Success, Try}
// - Central committer ledger implementations (sandboxes, KV...) may accept non-suffixed CID
// - Distributed ledger implementations (e.g. Canton) must reject non-suffixed CID
final class ContractIdIT extends LedgerTestSuite {
implicit val contractCompanion
: ContractCompanion.WithoutKey[Contract.Contract$, Contract.ContractId, Contract] =
Contract.COMPANION
implicit val contractRefCompanion: ContractCompanion.WithKey[
ContractRef.Contract,
ContractRef.ContractId,
ContractRef,
String,
] = ContractRef.COMPANION
List(
// Support for v0 contract ids existed only in sandbox-classic in
// SDK 1.18 and older and has been dropped completely.
@ -110,19 +119,19 @@ final class ContractIdIT extends LedgerTestSuite {
test("create payload") { implicit ec => (alpha, party) =>
alpha
.create(party, ContractRef(party, ContractId(example)))
.create(party, new ContractRef(party, new Contract.ContractId(example)))
.transformWith(Future.successful)
}
test("exercise target", parseErrorCode = LedgerApiErrors.RequestValidation.InvalidField) {
implicit ec => (alpha, party) =>
for {
contractCid <- alpha.create(party, Contract(party))
contractCid <- alpha.create(party, new Contract(party))
result <-
alpha
.exercise(
party,
ContractId[ContractRef](example).exerciseChange(contractCid),
new ContractRef.ContractId(example).exerciseChange(contractCid),
)
.transformWith(Future.successful)
} yield result match {
@ -142,21 +151,21 @@ final class ContractIdIT extends LedgerTestSuite {
test("choice argument") { implicit ec => (alpha, party) =>
for {
contractCid <- alpha.create(party, Contract(party))
contractRefCid <- alpha.create(party, ContractRef(party = party, ref = contractCid))
contractCid <- alpha.create(party, new Contract(party))
contractRefCid <- alpha.create(party, new ContractRef(party, contractCid))
result <- alpha
.exercise(party, contractRefCid.exerciseChange(ContractId(example)))
.exercise(party, contractRefCid.exerciseChange(new Contract.ContractId(example)))
.transformWith(Future.successful)
} yield result
}
test("create-and-exercise payload") { implicit ec => (alpha, party) =>
for {
contractCid <- alpha.create(party, Contract(party))
contractCid <- alpha.create(party, new Contract(party))
result <- alpha
.exercise(
party,
ContractRef(party = party, ref = ContractId(example)).createAnd
new ContractRef(party, new Contract.ContractId(example)).createAnd
.exerciseChange(contractCid),
)
.transformWith(Future.successful)
@ -165,12 +174,12 @@ final class ContractIdIT extends LedgerTestSuite {
test("create-and-exercise choice argument") { implicit ec => (alpha, party) =>
for {
contractCid <- alpha.create(party, Contract(party))
contractCid <- alpha.create(party, new Contract(party))
result <- alpha
.exercise(
party,
ContractRef(party = party, ref = contractCid).createAnd
.exerciseChange(ContractId(example)),
new ContractRef(party, contractCid).createAnd
.exerciseChange(new Contract.ContractId(example)),
)
.transformWith(Future.successful)
} yield result
@ -178,18 +187,16 @@ final class ContractIdIT extends LedgerTestSuite {
test("exercise by key") { implicit ec => (alpha, party) =>
for {
contractCid <- alpha.create(party, Contract(party))
_ <- alpha.create(party, ContractRef(party = party, ref = contractCid))
contractCid <- alpha.create(party, new Contract(party))
_ <- alpha.create(party, new ContractRef(party, contractCid))
result <- alpha
.exerciseByKey(
party,
ContractRef.id,
Value(Value.Sum.Party(Party.unwrap(party))),
ContractRef.TEMPLATE_ID,
party,
"Change",
Value(
Value.Sum.Record(
Record(None, List(RecordField("", Some(Value(Value.Sum.ContractId(example))))))
)
new DamlRecord(
new DamlRecord.Field(new ContractId(example))
),
)
.transformWith(Future.successful)

View File

@ -4,7 +4,6 @@
package com.daml.ledger.api.testtool.suites.v1_8
import java.util.regex.Pattern
import com.daml.error.definitions.LedgerApiErrors
import com.daml.ledger.api.testtool.infrastructure.Allocation._
import com.daml.ledger.api.testtool.infrastructure.Assertions._
@ -12,14 +11,18 @@ import com.daml.ledger.api.testtool.infrastructure.Eventually.eventually
import com.daml.ledger.api.testtool.infrastructure.LedgerTestSuite
import com.daml.ledger.api.testtool.infrastructure.Synchronize.synchronize
import com.daml.ledger.api.testtool.infrastructure.TransactionHelpers._
import com.daml.ledger.api.v1.value.{Record, RecordField, Value}
import com.daml.ledger.client.binding.Primitive.ContractId
import com.daml.ledger.test.model.DA.Types.Tuple2
import com.daml.ledger.test.model.Test
import com.daml.ledger.test.model.Test.CallablePayout
import scalaz.Tag
import com.daml.ledger.api.v1.value.{RecordField, Value}
import com.daml.ledger.javaapi.data.{DamlRecord, Party, Text}
import com.daml.ledger.test.java.model.da.types.Tuple2
import com.daml.ledger.test.java.model
import com.daml.ledger.test.java.model.test.{CallablePayout, WithKeyDivulgenceHelper}
import scala.jdk.CollectionConverters._
import scala.jdk.OptionConverters._
final class ContractKeysIT extends LedgerTestSuite {
import CompanionImplicits._
test(
"CKNoContractKey",
"There should be no contract key if the template does not specify one",
@ -27,7 +30,7 @@ final class ContractKeysIT extends LedgerTestSuite {
)(implicit ec => {
case Participants(Participant(alpha @ _, receiver), Participant(beta, giver)) =>
for {
_ <- beta.create(giver, CallablePayout(giver, receiver))
_ <- beta.create(giver, new CallablePayout(giver, receiver))
transactions <- beta.flatTransactions(giver, receiver)
} yield {
val contract = assertSingleton("NoContractKey", transactions.flatMap(createdEvents))
@ -43,13 +46,13 @@ final class ContractKeysIT extends LedgerTestSuite {
"Divulged contracts cannot be fetched or looked up by key by non-stakeholders",
allocate(SingleParty, SingleParty),
)(implicit ec => { case Participants(Participant(alpha, owner), Participant(beta, delegate)) =>
import Test.{Delegated, Delegation, ShowDelegated}
import model.test.{Delegated, Delegation, ShowDelegated}
val key = alpha.nextKeyId()
for {
// create contracts to work with
delegated <- alpha.create(owner, Delegated(owner, key))
delegation <- alpha.create(owner, Delegation(owner, delegate))
showDelegated <- alpha.create(owner, ShowDelegated(owner, delegate))
delegated <- alpha.create(owner, new Delegated(owner, key))
delegation <- alpha.create(owner, new Delegation(owner, delegate))
showDelegated <- alpha.create(owner, new ShowDelegated(owner, delegate))
// divulge the contract
_ <- alpha.exercise(owner, showDelegated.exerciseShowIt(delegated))
@ -91,12 +94,12 @@ final class ContractKeysIT extends LedgerTestSuite {
"Contract Keys should reject fetching an undisclosed contract",
allocate(SingleParty, SingleParty),
)(implicit ec => { case Participants(Participant(alpha, owner), Participant(beta, delegate)) =>
import Test.{Delegated, Delegation}
import model.test.{Delegated, Delegation}
val key = alpha.nextKeyId()
for {
// create contracts to work with
delegated <- alpha.create(owner, Delegated(owner, key))
delegation <- alpha.create(owner, Delegation(owner, delegate))
delegated <- alpha.create(owner, new Delegated(owner, key))
delegation <- alpha.create(owner, new Delegation(owner, delegate))
_ <- synchronize(alpha, beta)
@ -144,63 +147,69 @@ final class ContractKeysIT extends LedgerTestSuite {
"Contract keys should be scoped by maintainer",
allocate(SingleParty, SingleParty),
)(implicit ec => { case Participants(Participant(alpha, alice), Participant(beta, bob)) =>
import Test.{MaintainerNotSignatory, TextKey, TextKeyOperations}
import model.test.{MaintainerNotSignatory, TextKey, TextKeyOperations}
val key1 = alpha.nextKeyId()
val key2 = alpha.nextKeyId()
val unknownKey = alpha.nextKeyId()
for {
// create contracts to work with
tk1 <- alpha.create(alice, TextKey(alice, key1, List(bob)))
tk2 <- alpha.create(alice, TextKey(alice, key2, List(bob)))
aliceTKO <- alpha.create(alice, TextKeyOperations(alice))
bobTKO <- beta.create(bob, TextKeyOperations(bob))
tk1 <- alpha.create(alice, new TextKey(alice, key1, List(bob.getValue).asJava))
tk2 <- alpha.create(alice, new TextKey(alice, key2, List(bob.getValue).asJava))
aliceTKO <- alpha.create(alice, new TextKeyOperations(alice))
bobTKO <- beta.create(bob, new TextKeyOperations(bob))
_ <- synchronize(alpha, beta)
// creating a contract with a duplicate key should fail
duplicateKeyFailure <- alpha
.create(alice, TextKey(alice, key1, List(bob)))
.create(alice, new TextKey(alice, key1, List(bob.getValue).asJava))
.mustFail("creating a contract with a duplicate key")
// trying to lookup an unauthorized key should fail
bobLooksUpTextKeyFailure <- beta
.exercise(bob, bobTKO.exerciseTKOLookup(Tuple2(alice, key1), Some(tk1)))
.exercise(bob, bobTKO.exerciseTKOLookup(new Tuple2(alice, key1), Some(tk1).toJava))
.mustFail("looking up a contract with an unauthorized key")
// trying to lookup an unauthorized non-existing key should fail
bobLooksUpBogusTextKeyFailure <- beta
.exercise(bob, bobTKO.exerciseTKOLookup(Tuple2(alice, unknownKey), None))
.exercise(bob, bobTKO.exerciseTKOLookup(new Tuple2(alice, unknownKey), None.toJava))
.mustFail("looking up a contract with an unauthorized, non-existing key")
// successful, authorized lookup
_ <- alpha.exercise(alice, aliceTKO.exerciseTKOLookup(Tuple2(alice, key1), Some(tk1)))
_ <- alpha.exercise(
alice,
aliceTKO.exerciseTKOLookup(new Tuple2(alice, key1), Some(tk1).toJava),
)
// successful fetch
_ <- alpha.exercise(alice, aliceTKO.exerciseTKOFetch(Tuple2(alice, key1), tk1))
_ <- alpha.exercise(alice, aliceTKO.exerciseTKOFetch(new Tuple2(alice, key1), tk1))
// successful, authorized lookup of non-existing key
_ <- alpha.exercise(alice, aliceTKO.exerciseTKOLookup(Tuple2(alice, unknownKey), None))
_ <- alpha.exercise(
alice,
aliceTKO.exerciseTKOLookup(new Tuple2(alice, unknownKey), None.toJava),
)
// failing fetch
aliceFailedFetch <- alpha
.exercise(alice, aliceTKO.exerciseTKOFetch(Tuple2(alice, unknownKey), tk1))
.exercise(alice, aliceTKO.exerciseTKOFetch(new Tuple2(alice, unknownKey), tk1))
.mustFail("fetching a contract by an unknown key")
// now we exercise the contract, thus archiving it, and then verify
// that we cannot look it up anymore
_ <- alpha.exercise(alice, tk1.exerciseTextKeyChoice())
_ <- alpha.exercise(alice, aliceTKO.exerciseTKOLookup(Tuple2(alice, key1), None))
_ <- alpha.exercise(alice, aliceTKO.exerciseTKOLookup(new Tuple2(alice, key1), None.toJava))
// lookup the key, consume it, then verify we cannot look it up anymore
_ <- alpha.exercise(
alice,
aliceTKO.exerciseTKOConsumeAndLookup(tk2, Tuple2(alice, key2)),
aliceTKO.exerciseTKOConsumeAndLookup(tk2, new Tuple2(alice, key2)),
)
// failing create when a maintainer is not a signatory
maintainerNotSignatoryFailed <- alpha
.create(alice, MaintainerNotSignatory(alice, bob))
.create(alice, new MaintainerNotSignatory(alice, bob))
.mustFail("creating a contract where a maintainer is not a signatory")
} yield {
assertGrpcErrorRegex(
@ -238,23 +247,24 @@ final class ContractKeysIT extends LedgerTestSuite {
test("CKRecreate", "Contract keys can be recreated in single transaction", allocate(SingleParty))(
implicit ec => { case Participants(Participant(ledger, owner)) =>
import Test.Delegated
import model.test.Delegated
val key = ledger.nextKeyId()
for {
delegated1TxTree <- ledger
.submitAndWaitForTransactionTree(
ledger.submitAndWaitRequest(owner, Delegated(owner, key).create.command)
ledger.submitAndWaitRequest(owner, new Delegated(owner, key).create.commands)
)
.map(_.getTransaction)
delegated1Id = com.daml.ledger.client.binding.Primitive
.ContractId[Delegated](delegated1TxTree.eventsById.head._2.getCreated.contractId)
delegated1Id = new Delegated.ContractId(
delegated1TxTree.eventsById.head._2.getCreated.contractId
)
delegated2TxTree <- ledger.exercise(owner, delegated1Id.exerciseRecreate())
} yield {
assert(delegated2TxTree.eventsById.size == 2)
val event = delegated2TxTree.eventsById.filter(_._2.kind.isCreated).head._2
assert(
Tag.unwrap(delegated1Id) != event.getCreated.contractId,
delegated1Id.contractId != event.getCreated.contractId,
"New contract was not created",
)
assert(
@ -271,13 +281,13 @@ final class ContractKeysIT extends LedgerTestSuite {
"Contract keys created by transient contracts are properly archived",
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, owner)) =>
import Test.{Delegated, Delegation}
import model.test.{Delegated, Delegation}
val key = ledger.nextKeyId()
val key2 = ledger.nextKeyId()
for {
delegation <- ledger.create(owner, Delegation(owner, owner))
delegated <- ledger.create(owner, Delegated(owner, key))
delegation <- ledger.create(owner, new Delegation(owner, owner))
delegated <- ledger.create(owner, new Delegated(owner, key))
failedFetch <- ledger
.exercise(owner, delegation.exerciseFetchByKeyDelegated(owner, key2))
@ -304,10 +314,10 @@ final class ContractKeysIT extends LedgerTestSuite {
"The contract key should be exposed if the template specifies one",
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
import Test.TextKey
import model.test.TextKey
val expectedKey = ledger.nextKeyId()
for {
_ <- ledger.create(party, TextKey(party, expectedKey, List.empty))
_ <- ledger.create(party, new TextKey(party, expectedKey, List.empty.asJava))
transactions <- ledger.flatTransactions(party)
} yield {
val contract = assertSingleton("CKExposedByTemplate", transactions.flatMap(createdEvents))
@ -315,7 +325,7 @@ final class ContractKeysIT extends LedgerTestSuite {
"CKExposedByTemplate",
contract.getContractKey.getRecord.fields,
Seq(
RecordField("_1", Some(Value(Value.Sum.Party(Tag.unwrap(party))))),
RecordField("_1", Some(Value(Value.Sum.Party(party.getValue)))),
RecordField("_2", Some(Value(Value.Sum.Text(expectedKey)))),
),
)
@ -327,43 +337,37 @@ final class ContractKeysIT extends LedgerTestSuite {
"Exercising by key should be possible only when the corresponding contract is available",
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
import Test.TextKey
import model.test.TextKey
val keyString = ledger.nextKeyId()
val expectedKey = Value(
Value.Sum.Record(
Record(
fields = Seq(
RecordField("_1", Some(Value(Value.Sum.Party(Tag.unwrap(party))))),
RecordField("_2", Some(Value(Value.Sum.Text(keyString)))),
)
)
)
val expectedKey = new DamlRecord(
new DamlRecord.Field("_1", new Party(party.getValue)),
new DamlRecord.Field("_2", new Text(keyString)),
)
for {
failureBeforeCreation <- ledger
.exerciseByKey(
party,
TextKey.id,
TextKey.TEMPLATE_ID,
expectedKey,
"TextKeyChoice",
Value(Value.Sum.Record(Record())),
new DamlRecord(),
)
.mustFail("exercising before creation")
_ <- ledger.create(party, TextKey(party, keyString, List.empty))
_ <- ledger.create(party, new TextKey(party, keyString, List.empty.asJava))
_ <- ledger.exerciseByKey(
party,
TextKey.id,
TextKey.TEMPLATE_ID,
expectedKey,
"TextKeyChoice",
Value(Value.Sum.Record(Record())),
new DamlRecord(),
)
failureAfterConsuming <- ledger
.exerciseByKey(
party,
TextKey.id,
TextKey.TEMPLATE_ID,
expectedKey,
"TextKeyChoice",
Value(Value.Sum.Record(Record())),
new DamlRecord(),
)
.mustFail("exercising after consuming")
} yield {
@ -388,9 +392,12 @@ final class ContractKeysIT extends LedgerTestSuite {
allocate(SingleParty, SingleParty),
)(implicit ec => {
case Participants(Participant(ledger1, party1), Participant(ledger2, party2)) =>
import Test.LocalKeyVisibilityOperations
import model.test.LocalKeyVisibilityOperations
for {
ops <- ledger1.create(party1, LocalKeyVisibilityOperations(party1, party2))
ops: LocalKeyVisibilityOperations.ContractId <- ledger1.create(
party1,
new LocalKeyVisibilityOperations(party1, party2),
)
_ <- synchronize(ledger1, ledger2)
_ <- ledger2.exercise(party2, ops.exerciseLocalLookup())
} yield ()
@ -402,9 +409,12 @@ final class ContractKeysIT extends LedgerTestSuite {
allocate(SingleParty, SingleParty),
)(implicit ec => {
case Participants(Participant(ledger1, party1), Participant(ledger2, party2)) =>
import Test.LocalKeyVisibilityOperations
import model.test.LocalKeyVisibilityOperations
for {
ops <- ledger1.create(party1, LocalKeyVisibilityOperations(party1, party2))
ops: LocalKeyVisibilityOperations.ContractId <- ledger1.create(
party1,
new LocalKeyVisibilityOperations(party1, party2),
)
_ <- synchronize(ledger1, ledger2)
_ <- ledger2.exercise(party2, ops.exerciseLocalFetch())
} yield ()
@ -416,17 +426,22 @@ final class ContractKeysIT extends LedgerTestSuite {
allocate(SingleParty, SingleParty),
)(implicit ec => {
case Participants(Participant(ledger1, party1), Participant(ledger2, party2)) =>
import Test.{WithKey, WithKeyCreator, WithKeyFetcher}
import model.test.{WithKey, WithKeyCreator, WithKeyFetcher}
for {
// Create a helper contract and exercise a choice creating and disclosing a WithKey contract
creator1 <- ledger1.create(party1, WithKeyCreator(party1, party2))
withKey1 <- ledger1.exerciseAndGetContract[WithKey](
party1,
creator1.exerciseWithKeyCreator_DiscloseCreate(party1),
creator1 <- ledger1.create(party1, new WithKeyCreator(party1, party2))(
WithKeyCreator.COMPANION
)
withKey1 <- ledger1
.exerciseAndGetContract[WithKey.ContractId, WithKey](
party1,
creator1.exerciseWithKeyCreator_DiscloseCreate(party1),
)
// Verify that the withKey1 contract is usable by the party2
fetcher <- ledger1.create(party1, WithKeyFetcher(party1, party2))
fetcher <- ledger1.create(party1, new WithKeyFetcher(party1, party2))(
WithKeyFetcher.COMPANION
)
_ <- synchronize(ledger1, ledger2)
@ -443,8 +458,10 @@ final class ContractKeysIT extends LedgerTestSuite {
.mustFail("fetching an archived contract")
// Repeat the same steps for the second time
creator2 <- ledger1.create(party1, WithKeyCreator(party1, party2))
_ <- ledger1.exerciseAndGetContract[WithKey](
creator2 <- ledger1.create(party1, new WithKeyCreator(party1, party2))(
WithKeyCreator.COMPANION
)
_ <- ledger1.exerciseAndGetContract[model.test.WithKey.ContractId, model.test.WithKey](
party1,
creator2.exerciseWithKeyCreator_DiscloseCreate(party1),
)
@ -460,10 +477,13 @@ final class ContractKeysIT extends LedgerTestSuite {
allocate(SingleParty, SingleParty),
)(implicit ec => {
case Participants(Participant(ledger1, party1), Participant(ledger2, party2)) =>
import Test.{WithKey, WithKeyCreatorAlternative}
import model.test.{WithKey, WithKeyCreatorAlternative}
for {
// Create a helper contract and exercise a choice creating and disclosing a WithKey contract
creator1 <- ledger1.create(party1, WithKeyCreatorAlternative(party1, party2))
creator1: WithKeyCreatorAlternative.ContractId <- ledger1.create(
party1,
new WithKeyCreatorAlternative(party1, party2),
)(WithKeyCreatorAlternative.COMPANION)
_ <- synchronize(ledger1, ledger2)
@ -474,8 +494,8 @@ final class ContractKeysIT extends LedgerTestSuite {
_ <- synchronize(ledger1, ledger2)
Seq(withKey1Event) <- ledger1.activeContractsByTemplateId(List(WithKey.id), party1)
withKey1 = ContractId.apply[WithKey](withKey1Event.contractId)
Seq(withKey1Event) <- ledger1.activeContractsByTemplateId(List(WithKey.TEMPLATE_ID), party1)
withKey1 = new WithKey.ContractId(withKey1Event.contractId)
// Archive the disclosed contract
_ <- ledger1.exercise(party1, withKey1.exerciseArchive())
@ -499,18 +519,20 @@ final class ContractKeysIT extends LedgerTestSuite {
for {
// create contracts to work with
cid <- ledger.create(alice, Test.WithKey(alice))
cid <- ledger.create(alice, new model.test.WithKey(alice))
// double check its key can be found if visible
_ <- ledger.submit(
ledger.submitRequest(
alice,
Test.WithKey.key(alice).exerciseWithKey_NoOp(alice).command,
model.test.WithKey.byKey(alice).exerciseWithKey_NoOp(alice).commands,
)
)
// divulge the contract
helper <- ledger.create(bob, Test.WithKeyDivulgenceHelper(bob, alice))
helper <- ledger.create(bob, new model.test.WithKeyDivulgenceHelper(bob, alice))(
WithKeyDivulgenceHelper.COMPANION
)
_ <- ledger.exercise(alice, helper.exerciseWithKeyDivulgenceHelper_Fetch(cid))
// double check it is properly divulged
@ -519,16 +541,16 @@ final class ContractKeysIT extends LedgerTestSuite {
request = ledger.submitRequest(
bob,
// exercise by key the contract
Test.WithKey.key(alice).exerciseWithKey_NoOp(bob).command,
model.test.WithKey.byKey(alice).exerciseWithKey_NoOp(bob).commands,
)
failure1 <- ledger.submit(request).mustFail("exercise of a non visible key")
request = ledger.submitRequest(
bob,
// bring the contract in the engine cache
cid.exerciseWithKey_NoOp(bob).command,
// exercise by key the contract
Test.WithKey.key(alice).exerciseWithKey_NoOp(bob).command,
(cid.exerciseWithKey_NoOp(bob).commands.asScala ++
// exercise by key the contract
model.test.WithKey.byKey(alice).exerciseWithKey_NoOp(bob).commands.asScala).asJava,
)
failure2 <- ledger.submit(request).mustFail("exercise of a non visible key")

View File

@ -5,34 +5,38 @@ package com.daml.ledger.api.testtool.suites.v1_8
import com.daml.error.ErrorCode
import com.daml.error.definitions.LedgerApiErrors
import com.daml.ledger.api.refinements.ApiTypes.Party
import com.daml.ledger.api.testtool.infrastructure.Allocation._
import com.daml.ledger.api.testtool.infrastructure.Assertions._
import com.daml.ledger.api.testtool.infrastructure.LedgerTestSuite
import com.daml.ledger.api.testtool.infrastructure.participant.ParticipantTestContext
import com.daml.ledger.client.binding.Primitive
import com.daml.ledger.test.semantic.DeeplyNestedValue._
import com.daml.ledger.javaapi
import com.daml.ledger.javaapi.data.Party
import com.daml.ledger.javaapi.data.codegen.{ContractCompanion, Update}
import com.daml.ledger.test.java.semantic.deeplynestedvalue._
import scala.annotation.tailrec
import scala.concurrent.{ExecutionContext, Future}
import scala.util.Success
final class DeeplyNestedValueIT extends LedgerTestSuite {
implicit val handlerCompanion
: ContractCompanion.WithoutKey[Handler.Contract, Handler.ContractId, Handler] =
Handler.COMPANION
@tailrec
private[this] def toNat(i: Long, acc: Nat = Nat.Z(())): Nat =
if (i == 0) acc else toNat(i - 1, Nat.S(acc))
private[this] def toNat(i: Long, acc: Nat = new nat.Z(javaapi.data.Unit.getInstance)): Nat =
if (i == 0) acc else toNat(i - 1, new nat.S(acc))
private[this] def waitForTransactionId(
alpha: ParticipantTestContext,
party: Party,
command: Primitive.Update[_],
command: Update[_],
)(implicit
ec: ExecutionContext
): Future[Either[Throwable, String]] =
alpha
.submitAndWaitForTransactionId(
alpha.submitAndWaitRequest(party, command.command)
alpha.submitAndWaitRequest(party, command.commands)
)
.transform(x => Success(x.map(_.transactionId).toEither))
@ -85,7 +89,7 @@ final class DeeplyNestedValueIT extends LedgerTestSuite {
"create command",
LedgerApiErrors.CommandExecution.Preprocessing.PreprocessingFailed,
) { implicit ec => (alpha, party) =>
waitForTransactionId(alpha, party, Contract(party, nContract, toNat(nContract)).create)
waitForTransactionId(alpha, party, new Contract(party, nContract, toNat(nContract)).create)
}
test(
@ -93,7 +97,7 @@ final class DeeplyNestedValueIT extends LedgerTestSuite {
LedgerApiErrors.CommandExecution.Preprocessing.PreprocessingFailed,
) { implicit ec => (alpha, party) =>
for {
handler <- alpha.create(party, Handler(party))
handler: Handler.ContractId <- alpha.create(party, new Handler(party))
result <- waitForTransactionId(
alpha,
party,
@ -109,7 +113,7 @@ final class DeeplyNestedValueIT extends LedgerTestSuite {
waitForTransactionId(
alpha,
party,
Contract(party, nContract, toNat(nContract)).createAnd
new Contract(party, nContract, toNat(nContract)).createAnd
.exerciseArchive(),
)
}
@ -121,7 +125,7 @@ final class DeeplyNestedValueIT extends LedgerTestSuite {
waitForTransactionId(
alpha,
party,
Handler(party).createAnd.exerciseDestruct(toNat(nChoiceArgument)),
new Handler(party).createAnd.exerciseDestruct(toNat(nChoiceArgument)),
)
}
@ -130,7 +134,7 @@ final class DeeplyNestedValueIT extends LedgerTestSuite {
LedgerApiErrors.CommandExecution.Interpreter.ValueNesting,
) { implicit ec => (alpha, party) =>
for {
handler <- alpha.create(party, Handler(party))
handler: Handler.ContractId <- alpha.create(party, new Handler(party))
result <-
waitForTransactionId(
alpha,
@ -145,7 +149,7 @@ final class DeeplyNestedValueIT extends LedgerTestSuite {
LedgerApiErrors.CommandExecution.Interpreter.ValueNesting,
) { implicit ec => (alpha, party) =>
for {
handler <- alpha.create(party, Handler(party))
handler: Handler.ContractId <- alpha.create(party, new Handler(party))
result <-
waitForTransactionId(alpha, party, handler.exerciseConstruct(n))
} yield result
@ -156,7 +160,7 @@ final class DeeplyNestedValueIT extends LedgerTestSuite {
LedgerApiErrors.CommandExecution.Interpreter.ValueNesting,
) { implicit ec => (alpha, party) =>
for {
handler <- alpha.create(party, Handler(party))
handler: Handler.ContractId <- alpha.create(party, new Handler(party))
result <- waitForTransactionId(alpha, party, handler.exerciseCreate(nContract))
} yield result
}
@ -166,7 +170,7 @@ final class DeeplyNestedValueIT extends LedgerTestSuite {
LedgerApiErrors.CommandExecution.Interpreter.ValueNesting,
) { implicit ec => (alpha, party) =>
for {
handler <- alpha.create(party, Handler(party))
handler: Handler.ContractId <- alpha.create(party, new Handler(party))
result <- waitForTransactionId(alpha, party, handler.exerciseCreateKey(nKey))
} yield result
}
@ -179,7 +183,7 @@ final class DeeplyNestedValueIT extends LedgerTestSuite {
LedgerApiErrors.CommandExecution.Interpreter.ValueNesting,
) { implicit ec => (alpha, party) =>
for {
handler <- alpha.create(party, Handler(party))
handler: Handler.ContractId <- alpha.create(party, new Handler(party))
_ <- alpha.exercise(party, handler.exerciseCreateKey(nKey))
result <- waitForTransactionId(alpha, party, handler.exerciseFetchByKey(nKey))
} yield result
@ -191,7 +195,7 @@ final class DeeplyNestedValueIT extends LedgerTestSuite {
LedgerApiErrors.CommandExecution.Interpreter.ValueNesting,
) { implicit ec => (alpha, party) =>
for {
handler <- alpha.create(party, Handler(party))
handler: Handler.ContractId <- alpha.create(party, new Handler(party))
result <- waitForTransactionId(alpha, party, handler.exerciseLookupByKey(nKey))
} yield result
}
@ -204,7 +208,7 @@ final class DeeplyNestedValueIT extends LedgerTestSuite {
LedgerApiErrors.CommandExecution.Interpreter.ValueNesting,
) { implicit ec => (alpha, party) =>
for {
handler <- alpha.create(party, Handler(party))
handler: Handler.ContractId <- alpha.create(party, new Handler(party))
_ <- alpha.exercise(party, handler.exerciseCreateKey(nKey))
result <-
waitForTransactionId(alpha, party, handler.exerciseLookupByKey(nKey))

View File

@ -6,19 +6,26 @@ package com.daml.ledger.api.testtool.suites.v1_8
import com.daml.ledger.api.testtool.infrastructure.Allocation._
import com.daml.ledger.api.testtool.infrastructure.LedgerTestSuite
import com.daml.ledger.api.testtool.infrastructure.Synchronize.{synchronize, waitForContract}
import com.daml.ledger.test.model.Test
import scalaz.Tag
import com.daml.ledger.test.java.model.test.{
Asset,
Divulgence1,
Divulgence2,
Proposal,
WithKey,
WithKeyDivulgenceHelper,
}
final class DivulgenceIT extends LedgerTestSuite {
import CompanionImplicits._
test(
"DivulgenceTx",
"Divulged contracts should not be exposed by the transaction service",
allocate(TwoParties),
)(implicit ec => { case Participants(Participant(ledger, alice, bob)) =>
import Test.{Divulgence1, Divulgence2}
for {
divulgence1 <- ledger.create(alice, Divulgence1(alice))
divulgence2 <- ledger.create(bob, Divulgence2(bob, alice))
divulgence1 <- ledger.create(alice, new Divulgence1(alice))
divulgence2 <- ledger.create(bob, new Divulgence2(bob, alice))
_ <- ledger.exercise(alice, divulgence2.exerciseDivulgence2Archive(divulgence1))
bobTransactions <- ledger.flatTransactions(bob)
bobTrees <- ledger.transactionTrees(bob)
@ -33,7 +40,7 @@ final class DivulgenceIT extends LedgerTestSuite {
assert(
bobTransactions.size == 1,
s"$bob should see exactly one transaction but sees ${bobTransactions.size} instead",
s"${bob.getValue} should see exactly one transaction but sees ${bobTransactions.size} instead",
)
val events = bobTransactions.head.events
@ -50,7 +57,7 @@ final class DivulgenceIT extends LedgerTestSuite {
val contractId = event.created.get.contractId
assert(
contractId == divulgence2,
contractId == divulgence2.contractId,
s"The only visible event should be the creation of the second contract (expected $divulgence2, got $contractId instead)",
)
@ -82,7 +89,7 @@ final class DivulgenceIT extends LedgerTestSuite {
val createDivulgence2ContractId = createDivulgence2.getCreated.contractId
assert(
createDivulgence2ContractId == divulgence2,
createDivulgence2ContractId == divulgence2.contractId,
s"The event where Divulgence2 is created should have the same contract identifier as the created contract (expected $divulgence2, got $createDivulgence2ContractId instead)",
)
@ -100,7 +107,7 @@ final class DivulgenceIT extends LedgerTestSuite {
s"Expected event to be an exercise",
)
assert(exerciseOnDivulgence2.getExercised.contractId == divulgence2)
assert(exerciseOnDivulgence2.getExercised.contractId == divulgence2.contractId)
assert(exerciseOnDivulgence2.getExercised.childEventIds.size == 1)
@ -111,7 +118,7 @@ final class DivulgenceIT extends LedgerTestSuite {
assert(exerciseOnDivulgence1.kind.isExercised)
assert(exerciseOnDivulgence1.getExercised.contractId == divulgence1)
assert(exerciseOnDivulgence1.getExercised.contractId == divulgence1.contractId)
assert(exerciseOnDivulgence1.getExercised.childEventIds.isEmpty)
@ -140,12 +147,12 @@ final class DivulgenceIT extends LedgerTestSuite {
val firstCreationForBoth = firstEventForBoth.created.get
assert(
firstCreationForBoth.contractId == divulgence1,
firstCreationForBoth.contractId == divulgence1.contractId,
s"The creation seen by filtering for both $alice and $bob was expected to be $divulgence1 but is ${firstCreationForBoth.contractId} instead",
)
assert(
firstCreationForBoth.witnessParties == Seq(alice),
firstCreationForBoth.witnessParties == Seq(alice.getValue),
s"The creation seen by filtering for both $alice and $bob was expected to be witnessed by $alice but is instead ${firstCreationForBoth.witnessParties}",
)
}
@ -156,10 +163,9 @@ final class DivulgenceIT extends LedgerTestSuite {
"Divulged contracts should not be exposed by the active contract service",
allocate(TwoParties),
)(implicit ec => { case Participants(Participant(ledger, alice, bob)) =>
import Test.{Divulgence1, Divulgence2}
for {
divulgence1 <- ledger.create(alice, Divulgence1(alice))
divulgence2 <- ledger.create(bob, Divulgence2(bob, alice))
divulgence1 <- ledger.create(alice, new Divulgence1(alice))
divulgence2 <- ledger.create(bob, new Divulgence2(bob, alice))
_ <- ledger.exercise(alice, divulgence2.exerciseDivulgence2Fetch(divulgence1))
activeForBobOnly <- ledger.activeContracts(bob)
activeForBoth <- ledger.activeContracts(alice, bob)
@ -171,13 +177,13 @@ final class DivulgenceIT extends LedgerTestSuite {
s"$bob should see only one active contract but sees ${activeForBobOnly.size} instead",
)
assert(
activeForBobOnly.head.contractId == divulgence2,
activeForBobOnly.head.contractId == divulgence2.contractId,
s"$bob should see $divulgence2 but sees ${activeForBobOnly.head.contractId} instead",
)
// Since we're filtering for Bob only Bob will be the only reported witness even if Alice sees the contract
assert(
activeForBobOnly.head.witnessParties == Seq(bob),
activeForBobOnly.head.witnessParties == Seq(bob.getValue),
s"The witness parties as seen by $bob should only include him but it is instead ${activeForBobOnly.head.witnessParties}",
)
@ -186,8 +192,8 @@ final class DivulgenceIT extends LedgerTestSuite {
activeForBoth.size == 2,
s"The active contracts as seen by $alice and $bob should be two but are ${activeForBoth.size} instead",
)
val divulgence1ContractId = Tag.unwrap(divulgence1)
val divulgence2ContractId = Tag.unwrap(divulgence2)
val divulgence1ContractId = divulgence1.contractId
val divulgence2ContractId = divulgence2.contractId
val activeForBothContractIds = activeForBoth.map(_.contractId).sorted
val expectedContractIds = Seq(divulgence1ContractId, divulgence2ContractId).sorted
assert(
@ -199,11 +205,11 @@ final class DivulgenceIT extends LedgerTestSuite {
val divulgence2Witnesses =
activeForBoth.find(_.contractId == divulgence2ContractId).get.witnessParties.sorted
assert(
divulgence1Witnesses == Seq(alice),
divulgence1Witnesses == Seq(alice.getValue),
s"The witness parties of the first contract should only include $alice but it is instead $divulgence1Witnesses ($bob)",
)
assert(
divulgence2Witnesses == Tag.unsubst(Seq(alice, bob)).sorted,
divulgence2Witnesses == Seq(alice, bob).map(_.getValue).sorted,
s"The witness parties of the second contract should include $alice and $bob but it is instead $divulgence2Witnesses",
)
}
@ -214,10 +220,9 @@ final class DivulgenceIT extends LedgerTestSuite {
"Divulgence should behave as expected in a workflow involving keys",
allocate(SingleParty, SingleParty),
)(implicit ec => { case Participants(Participant(alpha, proposer), Participant(beta, owner)) =>
import Test.{Asset, Proposal}
for {
offer <- alpha.create(proposer, Proposal(from = proposer, to = owner))
asset <- beta.create(owner, Asset(issuer = owner, owner = owner))
offer <- alpha.create(proposer, new Proposal(proposer, owner))(Proposal.COMPANION)
asset <- beta.create(owner, new Asset(owner, owner))(Asset.COMPANION)
_ <- waitForContract(beta, owner, offer)
_ <- beta.exercise(owner, offer.exerciseProposalAccept(asset))
} yield {
@ -230,18 +235,17 @@ final class DivulgenceIT extends LedgerTestSuite {
"Divulging, archiving and divulging again a contract with key should be possible",
allocate(SingleParty, SingleParty),
)(implicit ec => { case Participants(Participant(alpha, partyA), Participant(beta, partyB)) =>
import Test.{WithKey, WithKeyDivulgenceHelper}
for {
// Create a helper contract where partyB is a signatory
helper <- beta.create(
partyB,
WithKeyDivulgenceHelper(divulgedTo = partyB, withKeyOwner = partyA),
)
new WithKeyDivulgenceHelper(partyB, partyA),
)(WithKeyDivulgenceHelper.COMPANION)
_ <- synchronize(alpha, beta)
// Create a WithKey contract owned by the partyA
withKey1 <- alpha.create(partyA, WithKey(partyA))
withKey1 <- alpha.create(partyA, new WithKey(partyA))
// Divulge the withKey1 contract
_ <- alpha.exercise(partyA, helper.exerciseWithKeyDivulgenceHelper_Fetch(withKey1))
@ -254,7 +258,7 @@ final class DivulgenceIT extends LedgerTestSuite {
_ <- synchronize(alpha, beta)
// Create another WithKey contract with the same key as previously
withKey2 <- alpha.create(partyA, WithKey(partyA))
withKey2 <- alpha.create(partyA, new WithKey(partyA))
// Divulge the withKey2 contract
_ <- alpha.exercise(partyA, helper.exerciseWithKeyDivulgenceHelper_Fetch(withKey2))

View File

@ -5,19 +5,26 @@ package com.daml.ledger.api.testtool.suites.v1_8
import java.util.UUID
import java.util.regex.Pattern
import com.daml.error.definitions.LedgerApiErrors
import com.daml.ledger.api.testtool.infrastructure.Allocation._
import com.daml.ledger.api.testtool.infrastructure.Assertions._
import com.daml.ledger.api.testtool.infrastructure.LedgerTestSuite
import com.daml.ledger.api.testtool.infrastructure.participant.ParticipantTestContext
import com.daml.ledger.client.binding.Primitive
import com.daml.ledger.client.binding.Primitive.{Party, List => PList}
import com.daml.ledger.test.model.Test._
import com.daml.ledger.javaapi.data.Party
import com.daml.ledger.javaapi.data.codegen.ContractCompanion
import com.daml.ledger.test.java.model.test._
import scala.concurrent.{ExecutionContext, Future}
import scala.jdk.CollectionConverters._
import scala.jdk.OptionConverters._
final class MultiPartySubmissionIT extends LedgerTestSuite {
implicit val multiPartyContractCompanion: ContractCompanion.WithKey[
MultiPartyContract.Contract,
MultiPartyContract.ContractId,
MultiPartyContract,
MultiPartyContract,
] = MultiPartyContract.COMPANION
test(
"MPSSubmit",
@ -28,7 +35,7 @@ final class MultiPartySubmissionIT extends LedgerTestSuite {
val request = ledger.submitRequest(
actAs = List(alice, bob),
readAs = List.empty,
commands = MultiPartyContract(PList(alice, bob), "").create.command,
commands = new MultiPartyContract(List(alice, bob).map(_.getValue).asJava, "").create.commands,
)
for {
@ -50,7 +57,7 @@ final class MultiPartySubmissionIT extends LedgerTestSuite {
_ <- ledger.create(
actAs = List(alice, bob),
readAs = List.empty,
template = MultiPartyContract(PList(alice, bob), ""),
template = new MultiPartyContract(List(alice, bob).map(_.getValue).asJava, ""),
)
} yield ()
})
@ -67,7 +74,7 @@ final class MultiPartySubmissionIT extends LedgerTestSuite {
.create(
actAs = List(alice, bob),
readAs = List.empty,
template = MultiPartyContract(PList(alice, bob, charlie), ""),
template = new MultiPartyContract(List(alice, bob, charlie).map(_.getValue).asJava, ""),
)
.mustFail("submitting a contract with a missing authorizers")
} yield {
@ -94,7 +101,8 @@ final class MultiPartySubmissionIT extends LedgerTestSuite {
_ <- ledger.exercise(
actAs = List(alice, bob, charlie, david),
readAs = List.empty,
exercise = contract.exerciseMPAddSignatories(PList(alice, bob, charlie, david)),
exercise =
contract.exerciseMPAddSignatories(List(alice, bob, charlie, david).map(_.getValue).asJava),
)
} yield ()
})
@ -114,7 +122,9 @@ final class MultiPartySubmissionIT extends LedgerTestSuite {
.exercise(
actAs = List(bob, charlie, david),
readAs = List.empty,
exercise = contract.exerciseMPAddSignatories(PList(alice, bob, charlie, david)),
exercise = contract.exerciseMPAddSignatories(
List(alice, bob, charlie, david).map(_.getValue).asJava
),
)
.mustFail("exercising a choice with a missing authorizers")
} yield {
@ -143,7 +153,8 @@ final class MultiPartySubmissionIT extends LedgerTestSuite {
_ <- ledger.exercise(
actAs = List(charlie, david),
readAs = List(alice),
exercise = contractB.exerciseMPFetchOther(contractA, PList(charlie, david)),
exercise =
contractB.exerciseMPFetchOther(contractA, List(charlie, david).map(_.getValue).asJava),
)
} yield ()
})
@ -166,7 +177,8 @@ final class MultiPartySubmissionIT extends LedgerTestSuite {
.exercise(
actAs = List(charlie, david),
readAs = List(bob, alice),
exercise = contractB.exerciseMPFetchOther(contractA, PList(charlie, david)),
exercise =
contractB.exerciseMPFetchOther(contractA, List(charlie, david).map(_.getValue).asJava),
)
.mustFail("exercising a choice without authorization to fetch another contract")
} yield {
@ -197,7 +209,8 @@ final class MultiPartySubmissionIT extends LedgerTestSuite {
.exercise(
actAs = List(charlie, david),
readAs = List.empty,
exercise = contractB.exerciseMPFetchOther(contractA, PList(charlie, david)),
exercise =
contractB.exerciseMPFetchOther(contractA, List(charlie, david).map(_.getValue).asJava),
)
.mustFail("exercising a choice without authorization to fetch another contract")
} yield {
@ -226,7 +239,8 @@ final class MultiPartySubmissionIT extends LedgerTestSuite {
_ <- ledger.exercise(
actAs = List(charlie, david),
readAs = List(alice),
exercise = contractB.exerciseMPFetchOtherByKey(keyA, PList(charlie, david)),
exercise =
contractB.exerciseMPFetchOtherByKey(keyA, List(charlie, david).map(_.getValue).asJava),
)
} yield ()
})
@ -249,7 +263,8 @@ final class MultiPartySubmissionIT extends LedgerTestSuite {
.exercise(
actAs = List(charlie, david),
readAs = List(bob, alice),
exercise = contractB.exerciseMPFetchOtherByKey(keyA, PList(charlie, david)),
exercise =
contractB.exerciseMPFetchOtherByKey(keyA, List(charlie, david).map(_.getValue).asJava),
)
.mustFail("exercising a choice without authorization to fetch another contract by key")
} yield {
@ -280,7 +295,8 @@ final class MultiPartySubmissionIT extends LedgerTestSuite {
.exercise(
actAs = List(charlie, david),
readAs = List.empty,
exercise = contractB.exerciseMPFetchOtherByKey(keyA, PList(charlie, david)),
exercise =
contractB.exerciseMPFetchOtherByKey(keyA, List(charlie, david).map(_.getValue).asJava),
)
.mustFail("exercising a choice without authorization to fetch another contract by key")
} yield {
@ -310,7 +326,11 @@ final class MultiPartySubmissionIT extends LedgerTestSuite {
actAs = List(charlie, david),
readAs = List(alice),
exercise = contractB
.exerciseMPLookupOtherByKey(keyA, PList(charlie, david), Some(contractA)),
.exerciseMPLookupOtherByKey(
keyA,
List(charlie, david).map(_.getValue).asJava,
Some(contractA).toJava,
),
)
} yield ()
})
@ -334,7 +354,11 @@ final class MultiPartySubmissionIT extends LedgerTestSuite {
actAs = List(charlie, david),
readAs = List(bob, alice),
exercise = contractB
.exerciseMPLookupOtherByKey(keyA, PList(charlie, david), Some(contractA)),
.exerciseMPLookupOtherByKey(
keyA,
List(charlie, david).map(_.getValue).asJava,
Some(contractA).toJava,
),
)
.mustFail("exercising a choice without authorization to look up another contract by key")
} yield {
@ -366,7 +390,11 @@ final class MultiPartySubmissionIT extends LedgerTestSuite {
actAs = List(charlie, david),
readAs = List.empty,
exercise = contractB
.exerciseMPLookupOtherByKey(keyA, PList(charlie, david), Some(contractA)),
.exerciseMPLookupOtherByKey(
keyA,
List(charlie, david).map(_.getValue).asJava,
Some(contractA).toJava,
),
)
.mustFail("exercising a choice without authorization to look up another contract by key")
} yield {
@ -393,12 +421,12 @@ final class MultiPartySubmissionIT extends LedgerTestSuite {
value: String = UUID.randomUUID().toString,
)(implicit
ec: ExecutionContext
): Future[(Primitive.ContractId[MultiPartyContract], MultiPartyContract)] =
): Future[(MultiPartyContract.ContractId, MultiPartyContract)] =
ledger
.create(
actAs = submitters,
readAs = List.empty,
template = MultiPartyContract(submitters, value),
template = new MultiPartyContract(submitters.map(_.getValue).asJava, value),
)
.map(cid => cid -> MultiPartyContract(submitters, value))
.map(cid => cid -> new MultiPartyContract(submitters.map(_.getValue).asJava, value))
}

View File

@ -10,8 +10,7 @@ import com.daml.ledger.api.testtool.infrastructure.Allocation._
import com.daml.ledger.api.testtool.infrastructure.Assertions._
import com.daml.ledger.api.testtool.infrastructure.LedgerTestSuite
import com.daml.ledger.test.PackageManagementTestDar
import com.daml.ledger.test.package_management.PackageManagementTest.PackageManagementTestTemplate
import com.daml.ledger.test.package_management.PackageManagementTest.PackageManagementTestTemplate._
import com.daml.ledger.test.java.package_management.packagemanagementtest.PackageManagementTestTemplate
import com.google.protobuf.ByteString
import scala.concurrent.{ExecutionContext, Future}
@ -71,7 +70,9 @@ final class PackageManagementServiceIT extends LedgerTestSuite {
testPackage <- loadTestPackage()
_ <- Future.sequence(Vector.fill(8)(ledger.uploadDarFile(testPackage)))
knownPackages <- ledger.listKnownPackages()
contract <- ledger.create(party, new PackageManagementTestTemplate(party))
contract <- ledger.create(party, new PackageManagementTestTemplate(party))(
PackageManagementTestTemplate.COMPANION
)
acsBefore <- ledger.activeContracts(party)
_ <- ledger.exercise(party, contract.exerciseTestChoice())
acsAfter <- ledger.activeContracts(party)

View File

@ -5,7 +5,6 @@ package com.daml.ledger.api.testtool.suites.v1_8
import java.util.regex.Pattern
import com.daml.error.definitions.LedgerApiErrors
import com.daml.ledger.api.refinements.ApiTypes
import com.daml.ledger.api.testtool.infrastructure.Allocation.{Participant, _}
import com.daml.ledger.api.testtool.infrastructure.Assertions._
import com.daml.ledger.api.testtool.infrastructure.{FutureAssertions, LedgerTestSuite}
@ -17,20 +16,28 @@ import com.daml.ledger.api.v1.event_query_service.{
GetEventsByContractIdRequest,
GetEventsByContractKeyRequest,
}
import com.daml.ledger.api.v1.value.{Record, RecordField, Value}
import com.daml.ledger.client.binding.Primitive
import com.daml.ledger.client.binding.Primitive.Party
import com.daml.ledger.test.model.Test.{Dummy, TextKey}
import com.daml.ledger.test.semantic.DivulgenceTests._
import com.daml.ledger.api.v1.value.{Identifier, Record, RecordField, Value}
import com.daml.ledger.javaapi.data.Party
import com.daml.ledger.javaapi.data.codegen.ContractCompanion
import com.daml.ledger.test.java.model.test.{Dummy, TextKey}
import com.daml.ledger.test.java.semantic.divulgencetests.{DivulgenceProposal, _}
import com.daml.ledger.test.java.semantic.divulgencetests
import com.daml.logging.LoggingContext
import scalaz.Tag
import scalaz.syntax.tag.ToTagOps
import scala.collection.immutable
import java.util.{List => JList}
import scala.concurrent.duration.DurationInt
import scala.concurrent.{ExecutionContext, Future}
class ParticipantPruningIT extends LedgerTestSuite {
import CompanionImplicits._
implicit val contractCompanion
: ContractCompanion.WithoutKey[Contract.Contract$, Contract.ContractId, Contract] =
Contract.COMPANION
implicit val semanticTestsDummyCompanion: ContractCompanion.WithoutKey[
divulgencetests.Dummy.Contract,
divulgencetests.Dummy.ContractId,
divulgencetests.Dummy,
] = divulgencetests.Dummy.COMPANION
private implicit val loggingContext: LoggingContext = LoggingContext.ForTesting
@ -71,23 +78,23 @@ class ParticipantPruningIT extends LedgerTestSuite {
ledger.latestPrunedOffsets()
// Move the ledger end forward
_ <- ledger.create(alice, Dummy(alice))
_ <- ledger.create(alice, new Dummy(alice))
firstPruningOffset <- ledger.currentEnd()
// Add one more element to bypass pruning to ledger end restriction
// and allow pruning at the first pruning offset
_ <- ledger.create(alice, Dummy(alice))
_ <- ledger.create(alice, new Dummy(alice))
secondPruningOffset <- ledger.currentEnd()
// Add one element to bypass pruning to ledger end restriction
// and allow pruning at the second pruning offset
_ <- ledger.create(alice, Dummy(alice))
_ <- ledger.create(alice, new Dummy(alice))
// Prune the ledger without divulgence at firstPruningOffset
_ <- ledger.pruneCantonSafe(
firstPruningOffset,
alice,
Dummy(_).create.command,
p => new Dummy(p).create.commands,
pruneAllDivulgedContracts = false,
)
(
@ -99,7 +106,7 @@ class ParticipantPruningIT extends LedgerTestSuite {
_ <- ledger.pruneCantonSafe(
firstPruningOffset,
alice,
Dummy(_).create.command,
p => new Dummy(p).create.commands,
pruneAllDivulgedContracts = true,
)
(
@ -111,7 +118,7 @@ class ParticipantPruningIT extends LedgerTestSuite {
_ <- ledger.pruneCantonSafe(
secondPruningOffset,
alice,
Dummy(_).create.command,
p => new Dummy(p).create.commands,
pruneAllDivulgedContracts = true,
)
(
@ -631,7 +638,7 @@ class ParticipantPruningIT extends LedgerTestSuite {
runConcurrently = false,
)(implicit ec => { case Participants(Participant(participant, submitter)) =>
for {
createdBeforePrune <- participant.create(submitter, Dummy(submitter))
createdBeforePrune: Dummy.ContractId <- participant.create(submitter, new Dummy(submitter))
offsets <- populateLedgerAndGetOffsets(participant, submitter)
offsetToPruneUpTo = offsets(lastItemToPruneIndex)
@ -691,16 +698,17 @@ class ParticipantPruningIT extends LedgerTestSuite {
)(implicit ec => { case Participants(Participant(participant, alice, bob)) =>
for {
divulgence <- createDivulgence(alice, bob, participant, participant)
contract <- participant.create(alice, Contract(alice))
contract <- participant.create(alice, new Contract(alice))
// Retroactively divulge Alice's contract to bob
_ <- participant.exercise(alice, divulgence.exerciseDivulge(contract))
// Bob can see the divulged contract
_ <- participant.exerciseAndGetContract[Dummy](
bob,
divulgence.exerciseCanFetch(contract),
)
_ <- participant
.exerciseAndGetContract[divulgencetests.Dummy.ContractId, divulgencetests.Dummy](
bob,
divulgence.exerciseCanFetch(contract),
)
_ <- pruneAtCurrentOffset(
participant,
@ -709,10 +717,11 @@ class ParticipantPruningIT extends LedgerTestSuite {
)
// Bob can still see the divulged contract
_ <- participant.exerciseAndGetContract[Dummy](
bob,
divulgence.exerciseCanFetch(contract),
)
_ <- participant
.exerciseAndGetContract[divulgencetests.Dummy.ContractId, divulgencetests.Dummy](
bob,
divulgence.exerciseCanFetch(contract),
)
// Archive the divulged contract
_ <- participant.exercise(alice, contract.exerciseArchive())
@ -724,7 +733,7 @@ class ParticipantPruningIT extends LedgerTestSuite {
)
_ <- participant
.exerciseAndGetContract[Dummy](
.exerciseAndGetContract[divulgencetests.Dummy.ContractId, divulgencetests.Dummy](
bob,
divulgence.exerciseCanFetch(contract),
)
@ -748,7 +757,7 @@ class ParticipantPruningIT extends LedgerTestSuite {
)(implicit ec => { case Participants(Participant(alpha, alice), Participant(beta, bob)) =>
for {
divulgence <- createDivulgence(alice, bob, alpha, beta)
contract <- alpha.create(alice, Contract(alice))
contract <- alpha.create(alice, new Contract(alice))
_ <- synchronize(alpha, beta) // because of exercise on beta inside createDivulgence
@ -773,10 +782,12 @@ class ParticipantPruningIT extends LedgerTestSuite {
for {
divulgence <- createDivulgence(alice, bob, alpha, beta)
divulgeNotDiscloseTemplate <- alpha.create(alice, DivulgeNotDiscloseTemplate(alice, bob))
divulgeNotDiscloseTemplate <- alpha.create(alice, new DivulgeNotDiscloseTemplate(alice, bob))(
DivulgeNotDiscloseTemplate.COMPANION
)
// Alice creates contract in a context not visible to Bob and follows with a divulgence to Bob in the same transaction
contract <- alpha.exerciseAndGetContract[Contract](
contract <- alpha.exerciseAndGetContractNoDisclose[Contract.ContractId](
alice,
divulgeNotDiscloseTemplate.exerciseDivulgeNoDisclose(divulgence),
)
@ -801,7 +812,7 @@ class ParticipantPruningIT extends LedgerTestSuite {
// synchronize to wait until alice has observed contract divulged by bob
_ <- synchronize(alpha, beta)
// Alice's contract creation is disclosed to Bob
contract <- alpha.exerciseAndGetContract[Contract](
contract <- alpha.exerciseAndGetContract[Contract.ContractId, Contract](
alice,
divulgence.exerciseCreateAndDisclose(),
)
@ -816,18 +827,21 @@ class ParticipantPruningIT extends LedgerTestSuite {
allocate(SingleParty),
runConcurrently = false,
)(implicit ec => { case Participants(Participant(participant, party)) =>
def getEvents(dummyCid: Primitive.ContractId[Dummy]): Future[Int] = {
val request = GetEventsByContractIdRequest(dummyCid.unwrap, immutable.Seq(party.unwrap))
def getEvents(dummyCid: Dummy.ContractId): Future[Int] = {
val request = GetEventsByContractIdRequest(dummyCid.contractId, Seq(party))
participant
.getEventsByContractId(request)
.map(r => r.createEvent.fold(0)(_ => 1) + r.archiveEvent.fold(0)(_ => 1))
}
for {
dummyCid <- participant.create(party, Dummy(party))
dummyCid: Dummy.ContractId <- participant.create(party, new Dummy(party))
end1 <- pruneToCurrentEnd(participant, party)
events1 <- getEvents(dummyCid)
exerciseCmd = participant.submitAndWaitRequest(party, dummyCid.exerciseDummyChoice1().command)
exerciseCmd = participant.submitAndWaitRequest(
party,
dummyCid.exerciseDummyChoice1().commands,
)
_ <- participant.submitAndWaitForTransactionTree(exerciseCmd)
events2 <- getEvents(dummyCid)
_ <- participant.prune(end1)
@ -859,19 +873,22 @@ class ParticipantPruningIT extends LedgerTestSuite {
.getEventsByContractKey(
GetEventsByContractKeyRequest(
contractKey = Some(key),
templateId = Some(TextKey.id.unwrap),
requestingParties = Tag.unsubst(immutable.Seq(party)),
templateId = Some(Identifier.fromJavaProto(TextKey.TEMPLATE_ID.toProto)),
requestingParties = Seq(party),
)
)
.map(r => r.createEvent.fold(0)(_ => 1) + r.archiveEvent.fold(0)(_ => 1))
for {
textKeyCid1 <- participant.create(party, TextKey(party, exercisedKey, Nil))
textKeyCid1: TextKey.ContractId <- participant.create(
party,
new TextKey(party, exercisedKey, JList.of()),
)
_ <- pruneToCurrentEnd(participant, party).map(_.getAbsolute)
events1 <- getEvents
exerciseCmd = participant.submitAndWaitRequest(
party,
textKeyCid1.exerciseTextKeyChoice().command,
textKeyCid1.exerciseTextKeyChoice().commands,
)
_ <- participant.submitAndWaitForTransactionTree(exerciseCmd)
events2 <- getEvents
@ -891,9 +908,14 @@ class ParticipantPruningIT extends LedgerTestSuite {
beta: ParticipantTestContext,
)(implicit ec: ExecutionContext) =
for {
divulgenceHelper <- alpha.create(alice, DivulgenceProposal(alice, bob))
divulgenceHelper <- alpha.create(alice, new DivulgenceProposal(alice, bob))(
DivulgenceProposal.COMPANION
)
_ <- synchronize(alpha, beta)
divulgence <- beta.exerciseAndGetContract[Divulgence](bob, divulgenceHelper.exerciseAccept())
divulgence <- beta.exerciseAndGetContract[Divulgence.ContractId, Divulgence](
bob,
divulgenceHelper.exerciseAccept(),
)(Divulgence.COMPANION)
} yield divulgence
private def divulgencePruneAndCheck(
@ -901,14 +923,14 @@ class ParticipantPruningIT extends LedgerTestSuite {
bob: Party,
alpha: ParticipantTestContext,
beta: ParticipantTestContext,
contract: Primitive.ContractId[Contract],
divulgence: Primitive.ContractId[Divulgence],
contract: Contract.ContractId,
divulgence: Divulgence.ContractId,
)(implicit ec: ExecutionContext) =
for {
_ <- synchronize(alpha, beta)
// Check that Bob can fetch the contract
_ <- beta.exerciseAndGetContract[Dummy](
_ <- beta.exerciseAndGetContract[divulgencetests.Dummy.ContractId, divulgencetests.Dummy](
bob,
divulgence.exerciseCanFetch(contract),
)
@ -916,7 +938,7 @@ class ParticipantPruningIT extends LedgerTestSuite {
offsetAfterDivulgence_1 <- beta.currentEnd()
// Alice re-divulges the contract to Bob
_ <- alpha.exerciseAndGetContract[Contract](
_ <- alpha.exerciseAndGetContractNoDisclose[divulgencetests.Dummy.ContractId](
alice,
divulgence.exerciseDivulge(contract),
)
@ -924,7 +946,7 @@ class ParticipantPruningIT extends LedgerTestSuite {
_ <- synchronize(alpha, beta)
// Check that Bob can fetch the contract
_ <- beta.exerciseAndGetContract[Dummy](
_ <- beta.exerciseAndGetContract[divulgencetests.Dummy.ContractId, divulgencetests.Dummy](
bob,
divulgence.exerciseCanFetch(contract),
)
@ -938,7 +960,7 @@ class ParticipantPruningIT extends LedgerTestSuite {
pruneAllDivulgedContracts = true,
)
// Check that Bob can still fetch the contract after pruning the first transaction
_ <- beta.exerciseAndGetContract[Dummy](
_ <- beta.exerciseAndGetContract[divulgencetests.Dummy.ContractId, divulgencetests.Dummy](
bob,
divulgence.exerciseCanFetch(contract),
)
@ -949,7 +971,7 @@ class ParticipantPruningIT extends LedgerTestSuite {
_ <- pruneAtCurrentOffset(beta, bob, pruneAllDivulgedContracts = true)
_ <- beta
.exerciseAndGetContract[Dummy](
.exerciseAndGetContract[divulgencetests.Dummy.ContractId, divulgencetests.Dummy](
bob,
divulgence.exerciseCanFetch(contract),
)
@ -992,9 +1014,9 @@ class ParticipantPruningIT extends LedgerTestSuite {
_ <- Future
.sequence(Vector.fill(batchesToPopulate) {
for {
dummy <- participant.create(submitter, Dummy(submitter))
dummy: Dummy.ContractId <- participant.create(submitter, new Dummy(submitter))
_ <- participant.exercise(submitter, dummy.exerciseDummyChoice1())
_ <- participant.create(submitter, Dummy(submitter))
_ <- participant.create(submitter, new Dummy(submitter))
} yield ()
})
trees <- participant.transactionTrees(
@ -1016,7 +1038,7 @@ class ParticipantPruningIT extends LedgerTestSuite {
_ <- populateLedgerAndGetOffsets(participant, localParty)
// Dummy needed to prune at this offset
_ <- participant.create(localParty, Dummy(localParty))
_ <- participant.create(localParty, new Dummy(localParty))
acsBeforePruning <- participant.activeContracts(localParty)
_ <- participant.prune(offset, pruneAllDivulgedContracts = pruneAllDivulgedContracts)
@ -1032,12 +1054,12 @@ class ParticipantPruningIT extends LedgerTestSuite {
// Note that the Daml template must be inspected to establish the key type and fields
// For the TextKey template the key is: (tkParty, tkKey) : (Party, Text)
// When populating the Record identifiers are not required.
private def makeTextKeyKey(party: ApiTypes.Party, keyText: String) = {
private def makeTextKeyKey(party: Party, keyText: String) = {
Value(
Value.Sum.Record(
Record(fields =
Vector(
RecordField(value = Some(Value(Value.Sum.Party(party.unwrap)))),
RecordField(value = Some(Value(Value.Sum.Party(party)))),
RecordField(value = Some(Value(Value.Sum.Text(keyText)))),
)
)
@ -1074,7 +1096,9 @@ class ParticipantPruningIT extends LedgerTestSuite {
"Pruning",
) {
for {
_ <- ledger.submitAndWait(ledger.submitAndWaitRequest(party, Dummy(party).create.command))
_ <- ledger.submitAndWait(
ledger.submitAndWaitRequest(party, new Dummy(party).create.commands)
)
_ <- ledger.prune(pruneUpTo = pruneUpTo, attempts = 1)
} yield ()
}

View File

@ -14,20 +14,18 @@ import com.daml.ledger.api.v1.admin.party_management_service.{
PartyDetails,
UpdatePartyIdentityProviderRequest,
}
import com.daml.ledger.client.binding
import com.daml.ledger.test.model.Test.Dummy
import com.daml.ledger.test.java.model.test.Dummy
import com.daml.lf.data.Ref
import scalaz.Tag
import scalaz.syntax.tag.ToTagOps
import java.util.regex.Pattern
import java.util.regex.Pattern
import com.daml.ledger.api.v1.admin.identity_provider_config_service.DeleteIdentityProviderConfigRequest
import com.daml.ledger.api.v1.admin.object_meta.ObjectMeta
import com.daml.ledger.client.binding.Primitive
import com.daml.ledger.javaapi.data.Party
import scala.util.Random
final class PartyManagementServiceIT extends PartyManagementITBase {
import CompanionImplicits._
test(
"PMUpdatingPartyIdentityProviderNonDefaultIdps",
@ -41,7 +39,7 @@ final class PartyManagementServiceIT extends PartyManagementITBase {
for {
_ <- ledger.createIdentityProviderConfig(identityProviderId = idpId1)
_ <- ledger.createIdentityProviderConfig(identityProviderId = idpId2)
party <- ledger.allocateParty(identityProviderId = Some(idpId1)).map(_.unwrap)
party <- ledger.allocateParty(identityProviderId = Some(idpId1))
get1 <- ledger.getParties(
GetPartiesRequest(parties = Seq(party), identityProviderId = idpId1)
)
@ -73,18 +71,18 @@ final class PartyManagementServiceIT extends PartyManagementITBase {
assertEquals(
"is idp1, request as idp1",
get1.partyDetails.map(d => d.identityProviderId -> d.party -> d.isLocal),
Seq(idpId1 -> party -> true),
Seq(idpId1 -> party.getValue -> true),
)
assertEquals(
"is idp2, request as idp2",
get2.partyDetails.map(d => d.identityProviderId -> d.party -> d.isLocal),
Seq(idpId2 -> party -> true),
Seq(idpId2 -> party.getValue -> true),
)
assertEquals(
"is idp2, request as idp1",
get3.partyDetails.map(d => d.identityProviderId -> d.party -> d.isLocal),
// party and isLocal values get blinded
Seq("" -> party -> false),
Seq("" -> party.getValue -> false),
)
}
@ -101,7 +99,7 @@ final class PartyManagementServiceIT extends PartyManagementITBase {
for {
_ <- ledger.createIdentityProviderConfig(identityProviderId = idpId1)
// allocate a party in the default idp
party <- ledger.allocateParty(identityProviderId = None).map(_.unwrap)
party <- ledger.allocateParty(identityProviderId = None)
get1 <- ledger.getParties(GetPartiesRequest(parties = Seq(party), identityProviderId = ""))
// Update party's idp id
_ <- ledger.updatePartyIdentityProviderId(
@ -127,12 +125,12 @@ final class PartyManagementServiceIT extends PartyManagementITBase {
assertEquals(
"default idp",
get1.partyDetails.map(d => d.identityProviderId -> d.party -> d.isLocal),
Seq("" -> party -> true),
Seq("" -> party.getValue -> true),
)
assertEquals(
"non default idp",
get2.partyDetails.map(d => d.identityProviderId -> d.party -> d.isLocal),
Seq(idpId1 -> party -> true),
Seq(idpId1 -> party.getValue -> true),
)
}
})
@ -146,7 +144,7 @@ final class PartyManagementServiceIT extends PartyManagementITBase {
)(implicit ec => { case Participants(Participant(ledger)) =>
val idpIdNonExistent = ledger.nextIdentityProviderId()
for {
party <- ledger.allocateParty(identityProviderId = None).map(_.unwrap)
party <- ledger.allocateParty(identityProviderId = None)
_ <- ledger
.updatePartyIdentityProviderId(
UpdatePartyIdentityProviderRequest(
@ -188,10 +186,10 @@ final class PartyManagementServiceIT extends PartyManagementITBase {
_ <- ledger.createIdentityProviderConfig(identityProviderId = idpIdNonDefault)
_ <- ledger.createIdentityProviderConfig(identityProviderId = idpIdMismatched)
_ <- ledger.createIdentityProviderConfig(identityProviderId = idpIdTarget)
partyDefault <- ledger.allocateParty(identityProviderId = None).map(_.unwrap)
partyDefault <- ledger.allocateParty(identityProviderId = None)
partyNonDefault <- ledger
.allocateParty(identityProviderId = Some(idpIdNonDefault))
.map(_.unwrap)
_ <- ledger
.updatePartyIdentityProviderId(
UpdatePartyIdentityProviderRequest(
@ -239,8 +237,8 @@ final class PartyManagementServiceIT extends PartyManagementITBase {
val idpId1 = ledger.nextIdentityProviderId()
for {
_ <- ledger.createIdentityProviderConfig(identityProviderId = idpId1)
partyDefault <- ledger.allocateParty(identityProviderId = None).map(_.unwrap)
partyNonDefault <- ledger.allocateParty(identityProviderId = Some(idpId1)).map(_.unwrap)
partyDefault <- ledger.allocateParty(identityProviderId = None)
partyNonDefault <- ledger.allocateParty(identityProviderId = Some(idpId1))
_ <- ledger.updatePartyIdentityProviderId(
UpdatePartyIdentityProviderRequest(
party = partyDefault,
@ -274,12 +272,12 @@ final class PartyManagementServiceIT extends PartyManagementITBase {
assertEquals(
"default idp",
get1.partyDetails.map(d => d.identityProviderId -> d.party -> d.isLocal),
Seq("" -> partyDefault -> true),
Seq("" -> partyDefault.getValue -> true),
)
assertEquals(
"non default idp",
get2.partyDetails.map(d => d.identityProviderId -> d.party -> d.isLocal),
Seq(idpId1 -> partyNonDefault -> true),
Seq(idpId1 -> partyNonDefault.getValue -> true),
)
}
})
@ -296,9 +294,9 @@ final class PartyManagementServiceIT extends PartyManagementITBase {
for {
_ <- ledger.createIdentityProviderConfig(identityProviderId = idpId1)
_ <- ledger.createIdentityProviderConfig(identityProviderId = idpId2)
partyDefault <- ledger.allocateParty(identityProviderId = None).map(_.unwrap)
partyNonDefault <- ledger.allocateParty(identityProviderId = Some(idpId1)).map(_.unwrap)
partyOtherNonDefault <- ledger.allocateParty(identityProviderId = Some(idpId2)).map(_.unwrap)
partyDefault <- ledger.allocateParty(identityProviderId = None)
partyNonDefault <- ledger.allocateParty(identityProviderId = Some(idpId1))
partyOtherNonDefault <- ledger.allocateParty(identityProviderId = Some(idpId2))
getAsDefaultIdp <- ledger.getParties(
GetPartiesRequest(parties = Seq(partyDefault, partyNonDefault), identityProviderId = "")
)
@ -369,7 +367,7 @@ final class PartyManagementServiceIT extends PartyManagementITBase {
displayName = Some("Bob Ross"),
)
} yield assert(
Tag.unwrap(party).nonEmpty,
party.getValue.nonEmpty,
"The allocated party identifier is an empty string",
)
})
@ -382,7 +380,7 @@ final class PartyManagementServiceIT extends PartyManagementITBase {
for {
party <- ledger.allocateParty(partyIdHint = None, displayName = Some("Jebediah Kerman"))
} yield assert(
Tag.unwrap(party).nonEmpty,
party.getValue.nonEmpty,
"The allocated party identifier is an empty string",
)
})
@ -471,7 +469,7 @@ final class PartyManagementServiceIT extends PartyManagementITBase {
displayName = None,
)
} yield assert(
Tag.unwrap(party).nonEmpty,
party.getValue.nonEmpty,
"The allocated party identifier is an empty string",
)
})
@ -492,7 +490,7 @@ final class PartyManagementServiceIT extends PartyManagementITBase {
partiesDetails <- ledger.getParties(Seq(party))
} yield {
assert(
Tag.unwrap(party).nonEmpty,
party.getValue.nonEmpty,
"The allocated party identifier is an empty string",
)
val partyDetails = assertSingleton("Only one party requested", partiesDetails)
@ -509,8 +507,8 @@ final class PartyManagementServiceIT extends PartyManagementITBase {
p1 <- ledger.allocateParty(partyIdHint = None, displayName = Some("Ononym McOmonymface"))
p2 <- ledger.allocateParty(partyIdHint = None, displayName = Some("Ononym McOmonymface"))
} yield {
assert(Tag.unwrap(p1).nonEmpty, "The first allocated party identifier is an empty string")
assert(Tag.unwrap(p2).nonEmpty, "The second allocated party identifier is an empty string")
assert(p1.getValue.nonEmpty, "The first allocated party identifier is an empty string")
assert(p2.getValue.nonEmpty, "The second allocated party identifier is an empty string")
assert(p1 != p2, "The two parties have the same party identifier")
}
})
@ -528,7 +526,7 @@ final class PartyManagementServiceIT extends PartyManagementITBase {
.mustFail("allocating a party with a duplicate hint")
} yield {
assert(
Tag.unwrap(party).nonEmpty,
party.getValue.nonEmpty,
"The allocated party identifier is an empty string",
)
assertGrpcErrorRegex(
@ -590,7 +588,7 @@ final class PartyManagementServiceIT extends PartyManagementITBase {
for {
parties <- ledger.allocateParties(100)
} yield {
val nonUniqueNames = parties.groupBy(Tag.unwrap).view.mapValues(_.size).filter(_._2 > 1).toMap
val nonUniqueNames = parties.groupBy(_.getValue).view.mapValues(_.size).filter(_._2 > 1).toMap
assert(
nonUniqueNames.isEmpty,
s"There are non-unique party names: ${nonUniqueNames
@ -626,22 +624,22 @@ final class PartyManagementServiceIT extends PartyManagementITBase {
),
)
partyDetails <- ledger.getParties(
Seq(party1, party2, binding.Primitive.Party("non-existent"))
Seq(party1, party2, new Party("non-existent"))
)
noPartyDetails <- ledger.getParties(Seq(binding.Primitive.Party("non-existent")))
noPartyDetails <- ledger.getParties(Seq(new Party("non-existent")))
zeroPartyDetails <- ledger.getParties(Seq.empty)
} yield {
assert(
partyDetails.sortBy(_.displayName).map(unsetResourceVersion) == Seq(
PartyDetails(
party = Ref.Party.assertFromString(Tag.unwrap(party1)),
party = Ref.Party.assertFromString(party1),
displayName = "Alice",
isLocal = true,
localMetadata =
if (useMeta) Some(ObjectMeta(annotations = Map("k1" -> "v1"))) else Some(ObjectMeta()),
),
PartyDetails(
party = Ref.Party.assertFromString(Tag.unwrap(party2)),
party = Ref.Party.assertFromString(party2),
displayName = "Bob",
isLocal = true,
localMetadata =
@ -682,7 +680,7 @@ final class PartyManagementServiceIT extends PartyManagementITBase {
displayName = None,
)
knownPartyResp <- ledger.listKnownPartiesResp()
knownPartyIds = knownPartyResp.partyDetails.map(_.party).map(Primitive.Party(_)).toSet
knownPartyIds = knownPartyResp.partyDetails.map(_.party).map(new Party(_)).toSet
} yield {
val allocatedPartyIds = Set(party1, party2, party3)
assert(
@ -690,27 +688,27 @@ final class PartyManagementServiceIT extends PartyManagementITBase {
s"The allocated party IDs $allocatedPartyIds are not a subset of $knownPartyIds.",
)
val fetchedAllocatedPartiesSet = knownPartyResp.partyDetails.collect {
case details if allocatedPartyIds.contains(Primitive.Party(details.party)) =>
case details if allocatedPartyIds.contains(new Party(details.party)) =>
unsetResourceVersion(details)
}.toSet
assertEquals(
fetchedAllocatedPartiesSet,
expected = Set(
PartyDetails(
party = party1.toString,
party = party1.getValue,
displayName = "",
isLocal = true,
localMetadata =
if (useMeta) Some(ObjectMeta(annotations = Map("k1" -> "v1"))) else Some(ObjectMeta()),
),
PartyDetails(
party = party2.toString,
party = party2.getValue,
displayName = "",
isLocal = true,
localMetadata = Some(ObjectMeta(annotations = Map.empty)),
),
PartyDetails(
party = party3.toString,
party = party3.getValue,
displayName = "",
isLocal = true,
localMetadata = Some(ObjectMeta(annotations = Map.empty)),
@ -727,18 +725,18 @@ final class PartyManagementServiceIT extends PartyManagementITBase {
)(implicit ec => { case Participants(Participant(alpha, alice), Participant(beta, bob)) =>
for {
// Running a dummy transaction seems to be required by the test framework to make parties visible via getParties
_ <- alpha.create(alice, Dummy(alice))
_ <- beta.create(bob, Dummy(bob))
_ <- alpha.create(alice, new Dummy(alice))
_ <- beta.create(bob, new Dummy(bob))
alphaParties <- alpha.getParties(Seq(alice, bob))
betaParties <- beta.getParties(Seq(alice, bob))
} yield {
assert(
alphaParties.exists(p => p.party == alice.unwrap && p.isLocal),
alphaParties.exists(p => p.party == alice.getValue && p.isLocal),
"Missing expected party from first participant",
)
assert(
betaParties.exists(p => p.party == bob.unwrap && p.isLocal),
betaParties.exists(p => p.party == bob.getValue && p.isLocal),
"Missing expected party from second participant",
)
@ -749,14 +747,14 @@ final class PartyManagementServiceIT extends PartyManagementITBase {
// participants with different ledger ids.
if (alpha.endpointId != beta.endpointId && alpha.ledgerId != beta.ledgerId) {
assert(
alphaParties.exists(p => p.party == bob.unwrap && !p.isLocal) || !alphaParties.exists(
_.party == bob.unwrap
alphaParties.exists(p => p.party == bob.getValue && !p.isLocal) || !alphaParties.exists(
_.party == bob.getValue
),
"Unexpected remote party marked as local found on first participant",
)
assert(
betaParties.exists(p => p.party == alice.unwrap && !p.isLocal) || !betaParties.exists(
_.party == alice.unwrap
betaParties.exists(p => p.party == alice.getValue && !p.isLocal) || !betaParties.exists(
_.party == alice.getValue
),
"Unexpected remote party marked as local found on second participant",
)

View File

@ -10,8 +10,9 @@ import com.daml.ledger.api.testtool.infrastructure.RaceConditionTests._
import com.daml.ledger.api.testtool.infrastructure.participant.ParticipantTestContext
import com.daml.ledger.api.v1.transaction.{TransactionTree, TreeEvent}
import com.daml.ledger.api.v1.value.RecordField
import com.daml.ledger.client.binding.Primitive
import com.daml.ledger.test.semantic.RaceTests._
import com.daml.ledger.javaapi.data.Party
import com.daml.ledger.javaapi.data.codegen.ContractCompanion
import com.daml.ledger.test.java.semantic.racetests._
import com.daml.timer.Delayed
import scala.annotation.nowarn
@ -20,6 +21,13 @@ import scala.concurrent.{ExecutionContext, Future}
import scala.util.Success
final class RaceConditionIT extends LedgerTestSuite {
implicit val contractWithKeyCompanion: ContractCompanion.WithKey[
ContractWithKey.Contract,
ContractWithKey.ContractId,
ContractWithKey,
String,
] = ContractWithKey.COMPANION
raceConditionTest(
"WWDoubleNonTransientCreate",
"Cannot concurrently create multiple non-transient contracts with the same key",
@ -28,7 +36,7 @@ final class RaceConditionIT extends LedgerTestSuite {
val attempts = (1 to 5).toVector
Future
.traverse(attempts) { _ =>
ledger.create(alice, ContractWithKey(alice)).transform(Success(_))
ledger.create(alice, new ContractWithKey(alice)).transform(Success(_))
}
.map { results =>
assertSingleton(
@ -46,7 +54,7 @@ final class RaceConditionIT extends LedgerTestSuite {
) { implicit ec => ledger => alice =>
val attempts = (1 to 5).toVector
for {
contract <- ledger.create(alice, ContractWithKey(alice))
contract <- ledger.create(alice, new ContractWithKey(alice))
_ <- Future.traverse(attempts) { _ =>
ledger.exercise(alice, contract.exerciseContractWithKey_Archive()).transform(Success(_))
}
@ -74,9 +82,9 @@ final class RaceConditionIT extends LedgerTestSuite {
with two consecutive successful contract creations.
*/
for {
contract <- ledger.create(alice, ContractWithKey(alice))
contract <- ledger.create(alice, new ContractWithKey(alice))
_ <- Delayed.by(500.millis)(())
createFuture = ledger.create(alice, ContractWithKey(alice)).transform(Success(_))
createFuture = ledger.create(alice, new ContractWithKey(alice)).transform(Success(_))
exerciseFuture = ledger
.exercise(alice, contract.exerciseContractWithKey_Archive())
.transform(Success(_))
@ -84,7 +92,9 @@ final class RaceConditionIT extends LedgerTestSuite {
_ <- exerciseFuture
_ <- ledger.create(
alice,
DummyContract(alice),
new DummyContract(alice),
)(
DummyContract.COMPANION
) // Create a dummy contract to ensure that we're not stuck with previous commands
transactions <- transactions(ledger, alice)
} yield {
@ -124,10 +134,12 @@ final class RaceConditionIT extends LedgerTestSuite {
"Cannot create a transient contract and a non-transient contract with the same key",
) { implicit ec => ledger => alice =>
for {
wrapper <- ledger.create(alice, CreateWrapper(alice))
wrapper: CreateWrapper.ContractId <- ledger.create(alice, new CreateWrapper(alice))(
CreateWrapper.COMPANION
)
_ <- executeRepeatedlyWithRandomDelay(
numberOfAttempts = 20,
once = ledger.create(alice, ContractWithKey(alice)).map(_ => ()),
once = ledger.create(alice, new ContractWithKey(alice)).map(_ => ()),
repeated =
ledger.exercise(alice, wrapper.exerciseCreateWrapper_CreateTransient()).map(_ => ()),
)
@ -150,7 +162,7 @@ final class RaceConditionIT extends LedgerTestSuite {
"Cannot exercise a choice after a contract archival",
) { implicit ec => ledger => alice =>
for {
contract <- ledger.create(alice, ContractWithKey(alice))
contract <- ledger.create(alice, new ContractWithKey(alice))
_ <- executeRepeatedlyWithRandomDelay(
numberOfAttempts = 10,
once = ledger.exercise(alice, contract.exerciseContractWithKey_Archive()),
@ -171,8 +183,10 @@ final class RaceConditionIT extends LedgerTestSuite {
"Cannot fetch an archived contract",
) { implicit ec => ledger => alice =>
for {
contract <- ledger.create(alice, ContractWithKey(alice))
fetchConract <- ledger.create(alice, FetchWrapper(alice, contract))
contract <- ledger.create(alice, new ContractWithKey(alice))
fetchConract <- ledger.create(alice, new FetchWrapper(alice, contract))(
FetchWrapper.COMPANION
)
_ <- executeRepeatedlyWithRandomDelay(
numberOfAttempts = 10,
once = ledger.exercise(alice, contract.exerciseContractWithKey_Archive()),
@ -193,8 +207,8 @@ final class RaceConditionIT extends LedgerTestSuite {
"Cannot successfully lookup by key an archived contract",
) { implicit ec => ledger => alice =>
for {
contract <- ledger.create(alice, ContractWithKey(alice))
looker <- ledger.create(alice, LookupWrapper(alice))
contract <- ledger.create(alice, new ContractWithKey(alice))
looker <- ledger.create(alice, new LookupWrapper(alice))(LookupWrapper.COMPANION)
_ <- executeRepeatedlyWithRandomDelay(
numberOfAttempts = 20,
once = ledger.exercise(alice, contract.exerciseContractWithKey_Archive()),
@ -215,10 +229,10 @@ final class RaceConditionIT extends LedgerTestSuite {
"Lookup by key cannot fail after a contract creation",
) { implicit ec => ledger => alice =>
for {
looker <- ledger.create(alice, LookupWrapper(alice))
looker <- ledger.create(alice, new LookupWrapper(alice))(LookupWrapper.COMPANION)
_ <- executeRepeatedlyWithRandomDelay(
numberOfAttempts = 5,
once = ledger.create(alice, ContractWithKey(alice)),
once = ledger.create(alice, new ContractWithKey(alice)),
repeated = ledger.exercise(alice, looker.exerciseLookupWrapper_Lookup()),
): @nowarn("cat=lint-infer-any")
transactions <- transactions(ledger, alice)
@ -239,7 +253,7 @@ final class RaceConditionIT extends LedgerTestSuite {
description: String,
repeated: Int = DefaultRepetitionsNumber,
runConcurrently: Boolean = false,
)(testCase: ExecutionContext => ParticipantTestContext => Primitive.Party => Future[Unit]): Unit =
)(testCase: ExecutionContext => ParticipantTestContext => Party => Future[Unit]): Unit =
test(
shortIdentifier = shortIdentifier,
description = description,

View File

@ -12,24 +12,31 @@ import com.daml.ledger.api.testtool.infrastructure.Synchronize.synchronize
import com.daml.ledger.api.testtool.infrastructure.TransactionHelpers._
import com.daml.ledger.api.testtool.infrastructure.participant.ParticipantTestContext
import com.daml.ledger.api.v1.value.{Record, RecordField, Value}
import com.daml.ledger.client.binding.Primitive
import com.daml.ledger.test.semantic.SemanticTests.Delegation._
import com.daml.ledger.test.semantic.SemanticTests.FetchIou._
import com.daml.ledger.test.semantic.SemanticTests.FetchPaintAgree._
import com.daml.ledger.test.semantic.SemanticTests.FetchPaintOffer._
import com.daml.ledger.test.semantic.SemanticTests.Iou._
import com.daml.ledger.test.semantic.SemanticTests.PaintCounterOffer._
import com.daml.ledger.test.semantic.SemanticTests.PaintOffer._
import com.daml.ledger.test.semantic.SemanticTests.SharedContract._
import com.daml.ledger.test.semantic.SemanticTests._
import scalaz.Tag
import com.daml.ledger.javaapi.data.Party
import com.daml.ledger.javaapi.data.codegen.ContractCompanion
import com.daml.ledger.test.java.semantic.semantictests.{PaintOffer, _}
import java.math.BigDecimal
import scala.concurrent.{ExecutionContext, Future}
import scala.jdk.CollectionConverters._
import scala.util.Success
final class SemanticTests extends LedgerTestSuite {
private[this] val onePound = Amount(BigDecimal(1), "GBP")
private[this] val twoPounds = Amount(BigDecimal(2), "GBP")
import CompanionImplicits._
implicit val delegationCompanion
: ContractCompanion.WithoutKey[Delegation.Contract, Delegation.ContractId, Delegation] =
Delegation.COMPANION
implicit val sharedContractCompanion: ContractCompanion.WithoutKey[
SharedContract.Contract,
SharedContract.ContractId,
SharedContract,
] = SharedContract.COMPANION
implicit val paintOfferCompanion
: ContractCompanion.WithoutKey[PaintOffer.Contract, PaintOffer.ContractId, PaintOffer] =
PaintOffer.COMPANION
private[this] val onePound = new Amount(BigDecimal.valueOf(1), "GBP")
private[this] val twoPounds = new Amount(BigDecimal.valueOf(2), "GBP")
/*
* Consistency
@ -52,7 +59,7 @@ final class SemanticTests extends LedgerTestSuite {
Participant(_, newOwner, leftWithNothing),
) =>
for {
iou <- alpha.create(payer, Iou(payer, owner, onePound))
iou <- alpha.create(payer, new Iou(payer, owner, onePound))
_ <- alpha.exercise(owner, iou.exerciseTransfer(newOwner))
failure <- alpha
.exercise(owner, iou.exerciseTransfer(leftWithNothing))
@ -84,7 +91,7 @@ final class SemanticTests extends LedgerTestSuite {
(f, c) =>
f.flatMap(_ =>
for {
shared <- alpha.create(payer, SharedContract(payer, owner1, owner2))
shared <- alpha.create(payer, new SharedContract(payer, owner1, owner2))
_ <- synchronize(alpha, beta)
results <- Future.traverse(1 to archives) {
case i if i % 2 == 0 =>
@ -116,11 +123,13 @@ final class SemanticTests extends LedgerTestSuite {
)(implicit ec => {
case Participants(Participant(alpha, payer, owner), Participant(_, newOwner1, newOwner2)) =>
for {
iou <- alpha.create(payer, Iou(payer, owner, onePound))
iou <- alpha.create(payer, new Iou(payer, owner, onePound))
doubleSpend = alpha.submitAndWaitRequest(
owner,
iou.exerciseTransfer(newOwner1).command,
iou.exerciseTransfer(newOwner2).command,
(iou.exerciseTransfer(newOwner1).commands.asScala ++ iou
.exerciseTransfer(newOwner2)
.commands
.asScala).asJava,
)
failure <- alpha.submitAndWait(doubleSpend).mustFail("consuming a contract twice")
} yield {
@ -140,7 +149,7 @@ final class SemanticTests extends LedgerTestSuite {
)(implicit ec => {
case Participants(Participant(alpha, payer, owner1), Participant(beta, owner2)) =>
for {
shared <- alpha.create(payer, SharedContract(payer, owner1, owner2))
shared <- alpha.create(payer, new SharedContract(payer, owner1, owner2))
_ <- alpha.exercise(owner1, shared.exerciseSharedContract_Consume1())
_ <- synchronize(alpha, beta)
failure <- beta
@ -173,24 +182,24 @@ final class SemanticTests extends LedgerTestSuite {
)(implicit ec => {
case Participants(Participant(alpha, bank, houseOwner), Participant(beta, painter)) =>
for {
iou <- alpha.create(bank, Iou(bank, houseOwner, onePound))
offer <- beta.create(painter, PaintOffer(painter, houseOwner, bank, onePound))
iou <- alpha.create(bank, new Iou(bank, houseOwner, onePound))
offer <- beta.create(painter, new PaintOffer(painter, houseOwner, bank, onePound))
tree <- eventually("Exercise paint offer") {
alpha.exercise(houseOwner, offer.exercisePaintOffer_Accept(iou))
}
} yield {
val agreement = assertSingleton(
"SemanticPaintOffer",
createdEvents(tree).filter(_.getTemplateId == Tag.unwrap(PaintAgree.id)),
createdEvents(tree).filter(_.getTemplateId == PaintAgree.TEMPLATE_ID.toV1),
)
assertEquals(
"Paint agreement parameters",
agreement.getCreateArguments,
Record(
recordId = Some(Tag.unwrap(PaintAgree.id)),
recordId = Some(PaintAgree.TEMPLATE_ID.toV1),
fields = Seq(
RecordField("painter", Some(Value(Value.Sum.Party(Tag.unwrap(painter))))),
RecordField("houseOwner", Some(Value(Value.Sum.Party(Tag.unwrap(houseOwner))))),
RecordField("painter", Some(Value(Value.Sum.Party(painter)))),
RecordField("houseOwner", Some(Value(Value.Sum.Party(houseOwner)))),
),
),
)
@ -204,13 +213,13 @@ final class SemanticTests extends LedgerTestSuite {
)(implicit ec => {
case Participants(Participant(alpha, bank, houseOwner), Participant(beta, painter)) =>
for {
iou <- alpha.create(bank, Iou(bank, houseOwner, onePound))
offer <- beta.create(painter, PaintOffer(painter, houseOwner, bank, twoPounds))
iou <- alpha.create(bank, new Iou(bank, houseOwner, onePound))
offer <- beta.create(painter, new PaintOffer(painter, houseOwner, bank, twoPounds))
counter <- eventually("exerciseAndGetContract") {
alpha.exerciseAndGetContract[PaintCounterOffer](
alpha.exerciseAndGetContract[PaintCounterOffer.ContractId, PaintCounterOffer](
houseOwner,
offer.exercisePaintOffer_Counter(iou),
)
)(PaintCounterOffer.COMPANION)
}
tree <- eventually("exercisePaintCounterOffer") {
beta.exercise(painter, counter.exercisePaintCounterOffer_Accept())
@ -218,16 +227,16 @@ final class SemanticTests extends LedgerTestSuite {
} yield {
val agreement = assertSingleton(
"SemanticPaintCounterOffer",
createdEvents(tree).filter(_.getTemplateId == Tag.unwrap(PaintAgree.id)),
createdEvents(tree).filter(_.getTemplateId == PaintAgree.TEMPLATE_ID.toV1),
)
assertEquals(
"Paint agreement parameters",
agreement.getCreateArguments,
Record(
recordId = Some(Tag.unwrap(PaintAgree.id)),
recordId = Some(PaintAgree.TEMPLATE_ID.toV1),
fields = Seq(
RecordField("painter", Some(Value(Value.Sum.Party(Tag.unwrap(painter))))),
RecordField("houseOwner", Some(Value(Value.Sum.Party(Tag.unwrap(houseOwner))))),
RecordField("painter", Some(Value(Value.Sum.Party(painter)))),
RecordField("houseOwner", Some(Value(Value.Sum.Party(houseOwner)))),
),
),
)
@ -241,7 +250,7 @@ final class SemanticTests extends LedgerTestSuite {
)(implicit ec => { case Participants(Participant(alpha, houseOwner), Participant(_, painter)) =>
for {
failure <- alpha
.create(houseOwner, PaintAgree(painter, houseOwner))
.create(houseOwner, new PaintAgree(painter, houseOwner))(PaintAgree.COMPANION)
.mustFail("creating a contract on behalf of two parties")
} yield {
assertGrpcError(
@ -260,8 +269,8 @@ final class SemanticTests extends LedgerTestSuite {
)(implicit ec => {
case Participants(Participant(alpha @ _, bank, houseOwner), Participant(beta, painter)) =>
for {
iou <- beta.create(painter, Iou(painter, houseOwner, onePound))
offer <- beta.create(painter, PaintOffer(painter, houseOwner, bank, onePound))
iou <- beta.create(painter, new Iou(painter, houseOwner, onePound))
offer <- beta.create(painter, new PaintOffer(painter, houseOwner, bank, onePound))
failure <- beta
.exercise(painter, offer.exercisePaintOffer_Accept(iou))
.mustFail("exercising a choice without consent")
@ -291,7 +300,7 @@ final class SemanticTests extends LedgerTestSuite {
)(implicit ec => {
case Participants(Participant(alpha, bank, houseOwner), Participant(beta, painter)) =>
for {
iou <- alpha.create(bank, Iou(bank, houseOwner, onePound))
iou <- alpha.create(bank, new Iou(bank, houseOwner, onePound))
_ <- synchronize(alpha, beta)
// The IOU should be visible only to the payer and the owner
@ -300,7 +309,7 @@ final class SemanticTests extends LedgerTestSuite {
iouFetchFailure <- fetchIou(beta, painter, iou)
.mustFail("fetching the IOU with the wrong party")
offer <- beta.create(painter, PaintOffer(painter, houseOwner, bank, onePound))
offer <- beta.create(painter, new PaintOffer(painter, houseOwner, bank, onePound))
_ <- synchronize(alpha, beta)
// The house owner and the painter can see the offer but the bank can't
@ -311,12 +320,12 @@ final class SemanticTests extends LedgerTestSuite {
tree <- alpha.exercise(houseOwner, offer.exercisePaintOffer_Accept(iou))
(newIouEvents, agreementEvents) = createdEvents(tree).partition(
_.getTemplateId == Tag.unwrap(Iou.id)
_.getTemplateId == Iou.TEMPLATE_ID.toV1
)
newIouEvent <- Future(newIouEvents.head)
agreementEvent <- Future(agreementEvents.head)
newIou = Primitive.ContractId[Iou](newIouEvent.contractId)
agreement = Primitive.ContractId[PaintAgree](agreementEvent.contractId)
newIou = new Iou.ContractId(newIouEvent.contractId)
agreement = new PaintAgree.ContractId(agreementEvent.contractId)
_ <- synchronize(alpha, beta)
// The Bank can see the new IOU, but it cannot see the PaintAgree contract
@ -363,31 +372,35 @@ final class SemanticTests extends LedgerTestSuite {
private def fetchIou(
ledger: ParticipantTestContext,
party: Primitive.Party,
iou: Primitive.ContractId[Iou],
party: Party,
iou: Iou.ContractId,
)(implicit ec: ExecutionContext): Future[Unit] =
for {
fetch <- ledger.create(party, FetchIou(party, iou))
fetch <- ledger.create(party, new FetchIou(party, iou))(FetchIou.COMPANION)
_ <- ledger.exercise(party, fetch.exerciseFetchIou_Fetch())
} yield ()
private def fetchPaintOffer(
ledger: ParticipantTestContext,
party: Primitive.Party,
paintOffer: Primitive.ContractId[PaintOffer],
party: Party,
paintOffer: PaintOffer.ContractId,
)(implicit ec: ExecutionContext): Future[Unit] =
for {
fetch <- ledger.create(party, FetchPaintOffer(party, paintOffer))
fetch <- ledger.create(party, new FetchPaintOffer(party, paintOffer))(
FetchPaintOffer.COMPANION
)
_ <- ledger.exercise(party, fetch.exerciseFetchPaintOffer_Fetch())
} yield ()
private def fetchPaintAgree(
ledger: ParticipantTestContext,
party: Primitive.Party,
agreement: Primitive.ContractId[PaintAgree],
party: Party,
agreement: PaintAgree.ContractId,
)(implicit ec: ExecutionContext): Future[Unit] =
for {
fetch <- ledger.create(party, FetchPaintAgree(party, agreement))
fetch <- ledger.create(party, new FetchPaintAgree(party, agreement))(
FetchPaintAgree.COMPANION
)
_ <- ledger.exercise(party, fetch.exerciseFetchPaintAgree_Fetch())
} yield ()
@ -399,11 +412,16 @@ final class SemanticTests extends LedgerTestSuite {
implicit ec => {
case Participants(Participant(alpha, issuer, owner), Participant(beta, delegate)) =>
for {
token <- alpha.create(issuer, Token(issuer, owner, 1))
delegation <- alpha.create(owner, Delegation(owner, delegate))
token <- alpha.create(issuer, new Token(issuer, owner, 1))(Token.COMPANION)
delegation <- alpha.create[Delegation.ContractId, Delegation](
owner,
new Delegation(owner, delegate),
)(Delegation.COMPANION)
// The owner tries to divulge with a non-consuming choice, which actually doesn't work
noDivulgeToken <- alpha.create(owner, Delegation(owner, delegate))
noDivulgeToken <- alpha.create(owner, new Delegation(owner, delegate))(
Delegation.COMPANION
)
_ <- alpha
.exercise(owner, noDivulgeToken.exerciseDelegation_Wrong_Divulge_Token(token))
_ <- synchronize(alpha, beta)
@ -412,7 +430,7 @@ final class SemanticTests extends LedgerTestSuite {
.mustFail("divulging with a non-consuming choice")
// Successful divulgence and delegation
divulgeToken <- alpha.create(owner, Delegation(owner, delegate))
divulgeToken <- alpha.create(owner, new Delegation(owner, delegate))(Delegation.COMPANION)
_ <- alpha.exercise(owner, divulgeToken.exerciseDelegation_Divulge_Token(token))
_ <- eventually("exerciseDelegation_Token_Consume") {
beta.exercise(delegate, delegation.exerciseDelegation_Token_Consume(token))

View File

@ -3,19 +3,20 @@
package com.daml.ledger.api.testtool.suites.v1_8
import java.time.Instant
import java.util.regex.Pattern
import com.daml.error.definitions.LedgerApiErrors
import com.daml.ledger.api.testtool.infrastructure.Allocation._
import com.daml.ledger.api.testtool.infrastructure.Assertions._
import com.daml.ledger.api.testtool.infrastructure.LedgerTestSuite
import com.daml.ledger.client.binding.{Primitive => P}
import com.daml.ledger.test.semantic.TimeTests._
import com.daml.ledger.javaapi.data.codegen.ContractCompanion
import com.daml.ledger.test.java.semantic.timetests._
import scala.concurrent.Future
final class TimeServiceIT extends LedgerTestSuite {
implicit val timecheckerCompanion
: ContractCompanion.WithoutKey[TimeChecker.Contract, TimeChecker.ContractId, TimeChecker] =
TimeChecker.COMPANION
test(
"TSTimeIsStatic",
@ -83,8 +84,8 @@ final class TimeServiceIT extends LedgerTestSuite {
)(implicit ec => { case Participants(Participant(ledger, party)) =>
for {
initialTime <- ledger.time()
thirtySecLater <- createTimestamp(initialTime.plusSeconds(30))
checker <- ledger.create(party, TimeChecker(party, thirtySecLater))
thirtySecLater = initialTime.plusSeconds(30)
checker <- ledger.create(party, new TimeChecker(party, thirtySecLater))
failure <- ledger
.exercise(party, checker.exerciseTimeChecker_CheckTime())
.mustFail("submitting choice prematurely")
@ -108,18 +109,11 @@ final class TimeServiceIT extends LedgerTestSuite {
)(implicit ec => { case Participants(Participant(ledger, party)) =>
for {
initialTime <- ledger.time()
thirtySecLater <- createTimestamp(initialTime.plusSeconds(30))
checker <- ledger.create(party, TimeChecker(party, thirtySecLater))
thirtySecLater = initialTime.plusSeconds(30)
checker <- ledger.create(party, new TimeChecker(party, thirtySecLater))
_ <- ledger.setTime(initialTime, initialTime.plusSeconds(30))
_ <- ledger.exercise(party, checker.exerciseTimeChecker_CheckTime())
} yield ()
})
def createTimestamp(seconds: Instant): Future[P.Timestamp] =
P.Timestamp
.discardNanos(seconds)
.fold(Future.failed[P.Timestamp](new IllegalStateException(s"Empty option")))(
Future.successful[P.Timestamp]
)
}

View File

@ -7,39 +7,46 @@ import com.daml.ledger.api.testtool.infrastructure.Allocation._
import com.daml.ledger.api.testtool.infrastructure.Assertions._
import com.daml.ledger.api.testtool.infrastructure.LedgerTestSuite
import com.daml.ledger.api.testtool.infrastructure.TransactionHelpers._
import com.daml.ledger.client.binding.Primitive
import com.daml.ledger.client.binding.Value.encode
import com.daml.ledger.test.model.Test.Choice1._
import com.daml.ledger.test.model.Test.Dummy._
import com.daml.ledger.test.model.Test.ParameterShowcase._
import com.daml.ledger.test.model.Test._
import com.daml.ledger.api.v1.value.Record.toJavaProto
import com.daml.ledger.api.v1.value.{Record, Value}
import com.daml.ledger.test.java.model.test._
import scala.collection.immutable.Seq
import java.math.BigDecimal
import java.util.{List => JList}
import scala.jdk.CollectionConverters._
import scala.jdk.OptionConverters._
class TransactionServiceArgumentsIT extends LedgerTestSuite {
import ClearIdsImplicits._
import CompanionImplicits._
test(
"TXCreateWithAnyType",
"Creates should not have issues dealing with any type of argument",
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
val template = ParameterShowcase(
operator = party,
integer = 42L,
decimal = BigDecimal("47.0000000000"),
text = "some text",
bool = true,
time = Primitive.Timestamp.MIN,
nestedOptionalInteger = NestedOptionalInteger(OptionalInteger.SomeInteger(-1L)),
integerList = Primitive.List(0L, 1L, 2L, 3L),
optionalText = Primitive.Optional("some optional text"),
val template = new ParameterShowcase(
party,
42L,
new BigDecimal("47.0000000000"),
"some text",
true,
TimestampConversion.MIN,
new NestedOptionalInteger(new optionalinteger.SomeInteger(-1L)),
JList.of(0, 1, 2, 3),
Some("some optional text").toJava,
)
val create = ledger.submitAndWaitRequest(party, template.create.command)
val create = ledger.submitAndWaitRequest(party, template.create.commands)
for {
transactionResponse <- ledger.submitAndWaitForTransaction(create)
} yield {
val transaction = transactionResponse.getTransaction
val contract = assertSingleton("CreateWithAnyType", createdEvents(transaction))
assertEquals("CreateWithAnyType", contract.getCreateArguments, template.arguments)
assertEquals(
"CreateWithAnyType",
contract.getCreateArguments.clearValueIds,
Record.fromJavaProto(template.toValue.toProtoRecord),
)
}
})
@ -48,20 +55,20 @@ class TransactionServiceArgumentsIT extends LedgerTestSuite {
"Exercise should not have issues dealing with any type of argument",
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
val template = ParameterShowcase(
operator = party,
integer = 42L,
decimal = BigDecimal("47.0000000000"),
text = "some text",
bool = true,
time = Primitive.Timestamp.MIN,
nestedOptionalInteger = NestedOptionalInteger(OptionalInteger.SomeInteger(-1L)),
integerList = Primitive.List(0L, 1L, 2L, 3L),
optionalText = Primitive.Optional("some optional text"),
val template = new ParameterShowcase(
party,
42L,
new BigDecimal("47.0000000000"),
"some text",
true,
TimestampConversion.MIN,
new NestedOptionalInteger(new optionalinteger.SomeInteger(-1L)),
List(0L, 1L, 2L, 3L).map(long2Long).asJava,
Some("some optional text").toJava,
)
val choice1 = Choice1(
val choice1 = new Choice1(
template.integer,
BigDecimal("37.0000000000"),
new BigDecimal("37.0000000000"),
template.text,
template.bool,
template.time,
@ -73,11 +80,15 @@ class TransactionServiceArgumentsIT extends LedgerTestSuite {
parameterShowcase <- ledger.create(
party,
template,
)
)(ParameterShowcase.COMPANION)
tree <- ledger.exercise(party, parameterShowcase.exerciseChoice1(choice1))
} yield {
val contract = assertSingleton("ExerciseWithAnyType", exercisedEvents(tree))
assertEquals("ExerciseWithAnyType", contract.getChoiceArgument, encode(choice1))
assertEquals(
"ExerciseWithAnyType",
clearIds(contract.getChoiceArgument),
Value.fromJavaProto(choice1.toValue.toProto),
)
}
})
@ -87,25 +98,29 @@ class TransactionServiceArgumentsIT extends LedgerTestSuite {
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
val n = 10000
val veryLongList = Primitive.List(List.iterate(0L, n)(_ + 1): _*)
val template = ParameterShowcase(
operator = party,
integer = 42L,
decimal = BigDecimal("47.0000000000"),
text = "some text",
bool = true,
time = Primitive.Timestamp.MIN,
nestedOptionalInteger = NestedOptionalInteger(OptionalInteger.SomeInteger(-1L)),
integerList = veryLongList,
optionalText = Primitive.Optional("some optional text"),
val veryLongList = List(List.iterate(0L, n)(_ + 1): _*).map(long2Long).asJava
val template = new ParameterShowcase(
party,
42L,
new BigDecimal("47.0000000000"),
"some text",
true,
TimestampConversion.MIN,
new NestedOptionalInteger(new optionalinteger.SomeInteger(-1L)),
veryLongList,
Some("some optional text").toJava,
)
val create = ledger.submitAndWaitRequest(party, template.create.command)
val create = ledger.submitAndWaitRequest(party, template.create.commands)
for {
transactionResponse <- ledger.submitAndWaitForTransaction(create)
} yield {
val transaction = transactionResponse.getTransaction
val contract = assertSingleton("VeryLongList", createdEvents(transaction))
assertEquals("VeryLongList", contract.getCreateArguments, template.arguments)
assertEquals(
"VeryLongList",
toJavaProto(contract.getCreateArguments.clearValueIds),
template.toValue.toProtoRecord,
)
}
})
@ -115,10 +130,10 @@ class TransactionServiceArgumentsIT extends LedgerTestSuite {
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
for {
dummy <- ledger.create(party, Dummy(party))
dummy: Dummy.ContractId <- ledger.create(party, new Dummy(party))
tree <- ledger.exercise(
party,
dummy.exerciseWrapWithAddress(Address("street", "city", "state", "zip")),
dummy.exerciseWrapWithAddress(new Address("street", "city", "state", "zip")),
)
} yield {
val contract = assertSingleton("Contract in transaction", createdEvents(tree))

View File

@ -9,23 +9,35 @@ import com.daml.ledger.api.testtool.infrastructure.Assertions._
import com.daml.ledger.api.testtool.infrastructure.Eventually.eventually
import com.daml.ledger.api.testtool.infrastructure.LedgerTestSuite
import com.daml.ledger.api.testtool.infrastructure.TransactionHelpers._
import com.daml.ledger.test.model.Test.Agreement._
import com.daml.ledger.test.model.Test.AgreementFactory._
import com.daml.ledger.test.model.Test.TriProposal._
import com.daml.ledger.test.model.Test._
import com.daml.ledger.api.v1.value.{Record, RecordField}
import com.daml.ledger.javaapi.data.codegen.ContractCompanion
import com.daml.ledger.test.java.model.test.{BranchingSignatories, _}
import scala.jdk.CollectionConverters._
class TransactionServiceAuthorizationIT extends LedgerTestSuite {
import CompanionImplicits._
implicit val triProposal
: ContractCompanion.WithoutKey[TriProposal.Contract, TriProposal.ContractId, TriProposal] =
TriProposal.COMPANION
test(
"TXRequireAuthorization",
"Require only authorization of chosen branching signatory",
allocate(SingleParty, SingleParty),
)(implicit ec => { case Participants(Participant(alpha, alice), Participant(_, bob)) =>
val template = BranchingSignatories(whichSign = true, signTrue = alice, signFalse = bob)
import ClearIdsImplicits._
val template = new BranchingSignatories(true, alice, bob)
for {
_ <- alpha.create(alice, template)
_ <- alpha.create(alice, template)(BranchingSignatories.COMPANION)
transactions <- alpha.flatTransactions(alice)
} yield {
assert(template.arguments == transactions.head.events.head.getCreated.getCreateArguments)
assert(
Record.fromJavaProto(
template.toValue.toProtoRecord
) == transactions.head.events.head.getCreated.getCreateArguments.clearValueIds
)
}
})
@ -36,11 +48,14 @@ class TransactionServiceAuthorizationIT extends LedgerTestSuite {
)(implicit ec => {
case Participants(Participant(alpha, operator, receiver), Participant(beta, giver)) =>
for {
agreementFactory <- beta.create(giver, AgreementFactory(receiver, giver))
agreementFactory <- beta.create(giver, new AgreementFactory(receiver, giver))
agreement <- eventually("exerciseAgreementFactoryAccept") {
alpha.exerciseAndGetContract(receiver, agreementFactory.exerciseAgreementFactoryAccept())
alpha.exerciseAndGetContract[Agreement.ContractId, Agreement](
receiver,
agreementFactory.exerciseAgreementFactoryAccept(),
)(Agreement.COMPANION)
}
triProposalTemplate = TriProposal(operator, receiver, giver)
triProposalTemplate = new TriProposal(operator, receiver, giver)
triProposal <- alpha.create(operator, triProposalTemplate)
tree <- eventually("exerciseAcceptTriProposal") {
beta.exercise(giver, agreement.exerciseAcceptTriProposal(triProposal))
@ -50,7 +65,9 @@ class TransactionServiceAuthorizationIT extends LedgerTestSuite {
assertEquals(
"AcceptTriProposal",
contract.getCreateArguments.fields,
triProposalTemplate.arguments.fields,
triProposalTemplate.toValue.getFields.asScala.map(rf =>
RecordField.fromJavaProto(rf.toProto)
),
)
}
})
@ -61,10 +78,15 @@ class TransactionServiceAuthorizationIT extends LedgerTestSuite {
allocate(SingleParty, SingleParty),
)(implicit ec => { case Participants(Participant(alpha, operator), Participant(beta, giver)) =>
for {
agreementFactory <- beta.create(giver, AgreementFactory(giver, giver))
agreementFactory <- beta.create(giver, new AgreementFactory(giver, giver))
agreement <-
beta.exerciseAndGetContract(giver, agreementFactory.exerciseAgreementFactoryAccept())
triProposalTemplate = TriProposal(operator, giver, giver)
beta.exerciseAndGetContract[Agreement.ContractId, Agreement](
giver,
agreementFactory.exerciseAgreementFactoryAccept(),
)(
Agreement.COMPANION
)
triProposalTemplate = new TriProposal(operator, giver, giver)
triProposal <- alpha.create(operator, triProposalTemplate)
tree <- eventually("exerciseAcceptTriProposal") {
beta.exercise(giver, agreement.exerciseAcceptTriProposal(triProposal))
@ -74,7 +96,9 @@ class TransactionServiceAuthorizationIT extends LedgerTestSuite {
assertEquals(
"AcceptTriProposalCoinciding",
contract.getCreateArguments.fields,
triProposalTemplate.arguments.fields,
triProposalTemplate.toValue.getFields.asScala.map(rf =>
RecordField.fromJavaProto(rf.toProto)
),
)
}
})
@ -86,7 +110,7 @@ class TransactionServiceAuthorizationIT extends LedgerTestSuite {
)(implicit ec => {
case Participants(Participant(alpha, operator, receiver), Participant(beta, giver)) =>
for {
triProposal <- alpha.create(operator, TriProposal(operator, receiver, giver))
triProposal <- alpha.create(operator, new TriProposal(operator, receiver, giver))
_ <- eventually("exerciseTriProposalAccept") {
for {
failure <- beta
@ -116,14 +140,17 @@ class TransactionServiceAuthorizationIT extends LedgerTestSuite {
)(implicit ec => {
case Participants(Participant(alpha, operator, receiver), Participant(beta, giver)) =>
for {
agreementFactory <- beta.create(giver, AgreementFactory(receiver, giver))
agreementFactory <- beta.create(giver, new AgreementFactory(receiver, giver))
// TODO eventually is a temporary workaround. It should take into account
// TODO that the contract needs to hit the target node before a choice
// TODO is executed on it.
agreement <- eventually("exerciseAgreementFactoryAccept") {
alpha.exerciseAndGetContract(receiver, agreementFactory.exerciseAgreementFactoryAccept())
alpha.exerciseAndGetContract[Agreement.ContractId, Agreement](
receiver,
agreementFactory.exerciseAgreementFactoryAccept(),
)(Agreement.COMPANION)
}
triProposalTemplate = TriProposal(operator, giver, giver)
triProposalTemplate = new TriProposal(operator, giver, giver)
triProposal <- alpha.create(operator, triProposalTemplate)
_ <- eventually("exerciseAcceptTriProposal") {
for {

View File

@ -11,14 +11,15 @@ import com.daml.ledger.api.testtool.suites.v1_8.TransactionServiceCorrectnessIT.
import com.daml.ledger.api.v1.event.Event.Event
import com.daml.ledger.api.v1.event.Event.Event.{Archived, Created, Empty}
import com.daml.ledger.api.v1.transaction.{Transaction, TransactionTree, TreeEvent}
import com.daml.ledger.test.model.Test.Dummy._
import com.daml.ledger.test.model.Test._
import com.daml.ledger.test.java.model.test._
import com.daml.ledger.api.testtool.infrastructure.EventOps.{EventOps, TreeEventOps}
import scala.collection.immutable.Seq
import scala.concurrent.Future
class TransactionServiceCorrectnessIT extends LedgerTestSuite {
import CompanionImplicits._
test(
"TXProcessInTwoChunks",
"Serve the complete sequence of transactions even if processing is stopped and resumed",
@ -26,13 +27,17 @@ class TransactionServiceCorrectnessIT extends LedgerTestSuite {
)(implicit ec => { case Participants(Participant(ledger, party)) =>
val transactionsToSubmit = 5
for {
_ <- Future.sequence(Vector.fill(transactionsToSubmit)(ledger.create(party, Dummy(party))))
_ <- Future.sequence(
Vector.fill(transactionsToSubmit)(ledger.create(party, new Dummy(party)))
)
endAfterFirstSection <- ledger.currentEnd()
firstSectionRequest = ledger
.getTransactionsRequest(ledger.transactionFilter(Seq(party)))
.update(_.end := endAfterFirstSection)
firstSection <- ledger.flatTransactions(firstSectionRequest)
_ <- Future.sequence(Vector.fill(transactionsToSubmit)(ledger.create(party, Dummy(party))))
_ <- Future.sequence(
Vector.fill(transactionsToSubmit)(ledger.create(party, new Dummy(party)))
)
endAfterSecondSection <- ledger.currentEnd()
secondSectionRequest = ledger
.getTransactionsRequest(ledger.transactionFilter(Seq(party)))
@ -59,7 +64,9 @@ class TransactionServiceCorrectnessIT extends LedgerTestSuite {
val transactionsToSubmit = 5
val parallelRequests = 10
for {
_ <- Future.sequence(Vector.fill(transactionsToSubmit)(ledger.create(party, Dummy(party))))
_ <- Future.sequence(
Vector.fill(transactionsToSubmit)(ledger.create(party, new Dummy(party)))
)
results <- Future.sequence(Vector.fill(parallelRequests)(ledger.flatTransactions(party)))
} yield {
assert(
@ -76,8 +83,8 @@ class TransactionServiceCorrectnessIT extends LedgerTestSuite {
allocate(TwoParties),
)(implicit ec => { case Participants(Participant(ledger, alice, bob)) =>
for {
_ <- ledger.create(alice, Dummy(alice))
_ <- ledger.create(bob, Dummy(bob))
_ <- ledger.create(alice, new Dummy(alice))
_ <- ledger.create(bob, new Dummy(bob))
aliceView <- ledger.flatTransactions(alice)
bobView <- ledger.flatTransactions(bob)
multiSubscriptionView <- ledger.flatTransactions(alice, bob)
@ -97,8 +104,8 @@ class TransactionServiceCorrectnessIT extends LedgerTestSuite {
allocate(TwoParties),
)(implicit ec => { case Participants(Participant(ledger, alice, bob)) =>
for {
_ <- ledger.create(alice, Dummy(alice))
_ <- ledger.create(bob, Dummy(bob))
_ <- ledger.create(alice, new Dummy(alice))
_ <- ledger.create(bob, new Dummy(bob))
aliceView <- ledger.transactionTrees(alice)
bobView <- ledger.transactionTrees(bob)
multiSubscriptionView <- ledger.transactionTrees(alice, bob)
@ -118,8 +125,8 @@ class TransactionServiceCorrectnessIT extends LedgerTestSuite {
allocate(SingleParty, SingleParty),
)(implicit ec => { case Participants(Participant(alpha, alice), Participant(beta, bob)) =>
for {
_ <- alpha.create(alice, AgreementFactory(bob, alice))
_ <- beta.create(bob, AgreementFactory(alice, bob))
_ <- alpha.create(alice, new AgreementFactory(bob, alice))
_ <- beta.create(bob, new AgreementFactory(alice, bob))
_ <- synchronize(alpha, beta)
alphaView <- alpha.flatTransactions(alice, bob)
betaView <- beta.flatTransactions(alice, bob)
@ -138,8 +145,8 @@ class TransactionServiceCorrectnessIT extends LedgerTestSuite {
allocate(SingleParty, SingleParty),
)(implicit ec => { case Participants(Participant(alpha, alice), Participant(beta, bob)) =>
for {
_ <- alpha.create(alice, AgreementFactory(bob, alice))
_ <- beta.create(bob, AgreementFactory(alice, bob))
_ <- alpha.create(alice, new AgreementFactory(bob, alice))
_ <- beta.create(bob, new AgreementFactory(alice, bob))
_ <- synchronize(alpha, beta)
alphaView <- alpha.transactionTrees(alice, bob)
betaView <- beta.transactionTrees(alice, bob)
@ -160,7 +167,7 @@ class TransactionServiceCorrectnessIT extends LedgerTestSuite {
)(implicit ec => {
case Participants(Participant(alpha, submitter), Participant(beta, listener)) =>
for {
_ <- alpha.create(submitter, AgreementFactory(listener, submitter))
_ <- alpha.create(submitter, new AgreementFactory(listener, submitter))
_ <- synchronize(alpha, beta)
trees <- alpha.transactionTrees(listener, submitter)
byId <- Future.sequence(
@ -183,7 +190,7 @@ class TransactionServiceCorrectnessIT extends LedgerTestSuite {
)(implicit ec => {
case Participants(Participant(alpha, submitter), Participant(beta, listener)) =>
for {
_ <- alpha.create(submitter, AgreementFactory(listener, submitter))
_ <- alpha.create(submitter, new AgreementFactory(listener, submitter))
_ <- synchronize(alpha, beta)
transactions <- alpha.flatTransactions(listener, submitter)
byId <- Future.sequence(
@ -209,8 +216,10 @@ class TransactionServiceCorrectnessIT extends LedgerTestSuite {
_ <- Future.sequence(
Vector.fill(contracts)(
ledger
.create(party, Dummy(party))
.flatMap(contract => ledger.exercise(party, contract.exerciseDummyChoice1()))
.create(party, new Dummy(party))
.flatMap((contract: Dummy.ContractId) =>
ledger.exercise(party, contract.exerciseDummyChoice1())
)
)
)
transactions <- ledger.flatTransactions(party)
@ -240,8 +249,10 @@ class TransactionServiceCorrectnessIT extends LedgerTestSuite {
_ <- Future.sequence(
Vector.fill(contracts)(
ledger
.create(party, Dummy(party))
.flatMap(contract => ledger.exercise(party, contract.exerciseDummyChoice1()))
.create(party, new Dummy(party))
.flatMap((contract: Dummy.ContractId) =>
ledger.exercise(party, contract.exerciseDummyChoice1())
)
)
)
transactions <- ledger.flatTransactions(party)
@ -284,8 +295,10 @@ class TransactionServiceCorrectnessIT extends LedgerTestSuite {
_ <- Future.sequence(
Vector.fill(contracts)(
ledger
.create(party, Dummy(party))
.flatMap(contract => ledger.exercise(party, contract.exerciseDummyChoice1()))
.create(party, new Dummy(party))
.flatMap((contract: Dummy.ContractId) =>
ledger.exercise(party, contract.exerciseDummyChoice1())
)
)
)
transactions <- ledger.flatTransactions(party)
@ -305,8 +318,10 @@ class TransactionServiceCorrectnessIT extends LedgerTestSuite {
_ <- Future.sequence(Vector.tabulate(contracts) { n =>
val party = if (n % 2 == 0) alice else bob
ledger
.create(party, Dummy(party))
.flatMap(contract => ledger.exercise(party, contract.exerciseDummyChoice1()))
.create(party, new Dummy(party))
.flatMap((contract: Dummy.ContractId) =>
ledger.exercise(party, contract.exerciseDummyChoice1())
)
})
transactions <- ledger.flatTransactions(alice, bob)
} yield {

View File

@ -10,31 +10,26 @@ import com.daml.ledger.api.testtool.infrastructure.Eventually.eventually
import com.daml.ledger.api.testtool.infrastructure.LedgerTestSuite
import com.daml.ledger.api.testtool.infrastructure.Synchronize.synchronize
import com.daml.ledger.api.testtool.infrastructure.TransactionHelpers._
import com.daml.ledger.client.binding.Primitive
import com.daml.ledger.test.model.Test.AgreementFactory._
import com.daml.ledger.test.model.Test.CreateAndFetch._
import com.daml.ledger.test.model.Test.Dummy._
import com.daml.ledger.test.model.Test.DummyFactory._
import com.daml.ledger.test.model.Test._
import scalaz.Tag
import com.daml.ledger.test.java.model.test._
class TransactionServiceExerciseIT extends LedgerTestSuite {
import CompanionImplicits._
test(
"TXUseCreateToExercise",
"Should be able to directly use a contract identifier to exercise a choice",
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
for {
dummyFactory <- ledger.create(party, DummyFactory(party))
dummyFactory <- ledger.create(party, new DummyFactory(party))
transactions <- ledger.exercise(party, dummyFactory.exerciseDummyFactoryCall())
} yield {
val events = transactions.rootEventIds.collect(transactions.eventsById)
val exercised = events.filter(_.kind.isExercised)
assert(exercised.size == 1, s"Only one exercise expected, got ${exercised.size}")
assert(
exercised.head.getExercised.contractId == Tag.unwrap(dummyFactory),
s"The identifier of the exercised contract should have been ${Tag
.unwrap(dummyFactory)} but instead it was ${exercised.head.getExercised.contractId}",
exercised.head.getExercised.contractId == dummyFactory.contractId,
s"The identifier of the exercised contract should have been ${dummyFactory.contractId} but instead it was ${exercised.head.getExercised.contractId}",
)
}
})
@ -45,27 +40,27 @@ class TransactionServiceExerciseIT extends LedgerTestSuite {
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
for {
factory <- ledger.create(party, DummyFactory(party))
factory <- ledger.create(party, new DummyFactory(party))
_ <- ledger.exercise(party, factory.exerciseDummyFactoryCall())
dummyWithParam <- ledger.flatTransactionsByTemplateId(DummyWithParam.id, party)
dummyFactory <- ledger.flatTransactionsByTemplateId(DummyFactory.id, party)
dummyWithParam <- ledger.flatTransactionsByTemplateId(DummyWithParam.TEMPLATE_ID, party)
dummyFactory <- ledger.flatTransactionsByTemplateId(DummyFactory.TEMPLATE_ID, party)
} yield {
val create = assertSingleton("GetCreate", dummyWithParam.flatMap(createdEvents))
assertEquals(
"Create should be of DummyWithParam",
create.getTemplateId,
Tag.unwrap(DummyWithParam.id),
DummyWithParam.TEMPLATE_ID.toV1,
)
val archive = assertSingleton("GetArchive", dummyFactory.flatMap(archivedEvents))
assertEquals(
"Archive should be of DummyFactory",
archive.getTemplateId,
Tag.unwrap(DummyFactory.id),
DummyFactory.TEMPLATE_ID.toV1,
)
assertEquals(
"Mismatching archived contract identifier",
archive.contractId,
Tag.unwrap(factory),
factory.contractId,
)
}
})
@ -76,7 +71,10 @@ class TransactionServiceExerciseIT extends LedgerTestSuite {
allocate(SingleParty, SingleParty),
)(implicit ec => { case Participants(Participant(alpha, receiver), Participant(beta, giver)) =>
for {
agreementFactory <- beta.create(giver, AgreementFactory(receiver, giver))
agreementFactory: AgreementFactory.ContractId <- beta.create(
giver,
new AgreementFactory(receiver, giver),
)
_ <- eventually("exerciseCreateAgreement") {
alpha.exercise(receiver, agreementFactory.exerciseCreateAgreement())
}
@ -96,7 +94,9 @@ class TransactionServiceExerciseIT extends LedgerTestSuite {
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
for {
createAndFetch <- ledger.create(party, CreateAndFetch(party))
createAndFetch: CreateAndFetch.ContractId <- ledger.create(party, new CreateAndFetch(party))(
CreateAndFetch.COMPANION
)
transaction <- ledger.exerciseForFlatTransaction(
party,
createAndFetch.exerciseCreateAndFetch_Run(),
@ -107,7 +107,7 @@ class TransactionServiceExerciseIT extends LedgerTestSuite {
assertSingleton("There should be only one archive", archivedEvents(transaction))
assertEquals(
"The contract identifier of the exercise does not match",
Tag.unwrap(createAndFetch),
createAndFetch.contractId,
exercise.contractId,
)
}
@ -119,12 +119,12 @@ class TransactionServiceExerciseIT extends LedgerTestSuite {
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
for {
dummy <- ledger.create(party, Dummy(party))
dummy: Dummy.ContractId <- ledger.create(party, new Dummy(party))
failure <- ledger
.exercise(
party,
dummy
.exerciseConsumeIfTimeIsBetween(Primitive.Timestamp.MAX, Primitive.Timestamp.MAX),
.exerciseConsumeIfTimeIsBetween(TimestampConversion.MAX, TimestampConversion.MAX),
)
.mustFail("exercising with a failing assertion")
} yield {

View File

@ -9,20 +9,24 @@ import com.daml.ledger.api.testtool.infrastructure.LedgerTestSuite
import com.daml.ledger.api.testtool.infrastructure.TransactionHelpers._
import com.daml.ledger.api.v1.event.CreatedEvent
import com.daml.ledger.api.v1.transaction.{Transaction, TransactionTree}
import com.daml.ledger.api.v1.value.RecordField
import com.daml.ledger.client.binding.Primitive
import com.daml.ledger.test.model.Test._
import com.daml.ledger.api.v1.value.{Record, RecordField}
import com.daml.ledger.javaapi.data.Party
import com.daml.ledger.test.java.model.test._
import scala.collection.immutable.Seq
import scala.jdk.OptionConverters._
class TransactionServiceOutputsIT extends LedgerTestSuite {
import ClearIdsImplicits._
import CompanionImplicits._
test(
"TXUnitAsArgumentToNothing",
"Daml engine returns Unit as argument to Nothing",
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
val template = NothingArgument(party, Primitive.Optional.empty)
val create = ledger.submitAndWaitRequest(party, template.create.command)
val template = new NothingArgument(party, None.toJava)
val create = ledger.submitAndWaitRequest(party, template.create.commands)
for {
transactionResponse <- ledger.submitAndWaitForTransaction(create)
} yield {
@ -30,7 +34,11 @@ class TransactionServiceOutputsIT extends LedgerTestSuite {
"UnitAsArgumentToNothing",
createdEvents(transactionResponse.getTransaction),
)
assertEquals("UnitAsArgumentToNothing", contract.getCreateArguments, template.arguments)
assertEquals(
"UnitAsArgumentToNothing",
contract.getCreateArguments.clearValueIds,
Record.fromJavaProto(template.toValue.toProtoRecord),
)
}
})
@ -40,11 +48,15 @@ class TransactionServiceOutputsIT extends LedgerTestSuite {
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
for {
_ <- ledger.create(party, Dummy(party))
transactions <- ledger.flatTransactionsByTemplateId(Dummy.id, party)
_ <- ledger.create(party, new Dummy(party))
transactions <- ledger.flatTransactionsByTemplateId(Dummy.TEMPLATE_ID, party)
} yield {
val contract = assertSingleton("AgreementText", transactions.flatMap(createdEvents))
assertEquals("AgreementText", contract.getAgreementText, s"'$party' operates a dummy.")
assertEquals(
"AgreementText",
contract.getAgreementText,
s"'${party.getValue}' operates a dummy.",
)
}
})
@ -54,7 +66,7 @@ class TransactionServiceOutputsIT extends LedgerTestSuite {
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
for {
_ <- ledger.create(party, DummyWithParam(party))
_ <- ledger.create(party, new DummyWithParam(party))
transactions <- ledger.flatTransactions(party)
} yield {
val contract = assertSingleton("AgreementTextDefault", transactions.flatMap(createdEvents))
@ -68,7 +80,7 @@ class TransactionServiceOutputsIT extends LedgerTestSuite {
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
for {
_ <- ledger.create(party, Dummy(party))
_ <- ledger.create(party, new Dummy(party))
request = ledger.getTransactionsRequest(ledger.transactionFilter(Seq(party)))
verboseTransactions <- ledger.flatTransactions(request.update(_.verbose := true))
verboseTransactionTrees <- ledger.transactionTrees(request.update(_.verbose := true))
@ -91,7 +103,7 @@ class TransactionServiceOutputsIT extends LedgerTestSuite {
})
private def assertLabelsAreExposedCorrectly(
party: Primitive.Party,
party: Party,
transactions: Seq[Transaction],
transactionTrees: Seq[TransactionTree],
labelIsNonEmpty: Boolean,

View File

@ -8,17 +8,18 @@ import com.daml.ledger.api.testtool.infrastructure.Allocation._
import com.daml.ledger.api.testtool.infrastructure.Assertions._
import com.daml.ledger.api.testtool.infrastructure.LedgerTestSuite
import com.daml.ledger.api.testtool.infrastructure.Synchronize.synchronize
import com.daml.ledger.test.model.Test.Dummy._
import com.daml.ledger.test.model.Test._
import com.daml.ledger.test.java.model.test._
class TransactionServiceQueryIT extends LedgerTestSuite {
import CompanionImplicits._
test(
"TXTransactionTreeByIdBasic",
"Expose a visible transaction tree by identifier",
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
for {
dummy <- ledger.create(party, Dummy(party))
dummy <- ledger.create(party, new Dummy(party))
tree <- ledger.exercise(party, dummy.exerciseDummyChoice1())
byId <- ledger.transactionTreeById(tree.transactionId, party)
} yield {
@ -32,7 +33,7 @@ class TransactionServiceQueryIT extends LedgerTestSuite {
allocate(SingleParty, SingleParty),
)(implicit ec => { case Participants(Participant(alpha, party), Participant(beta, intruder)) =>
for {
dummy <- alpha.create(party, Dummy(party))
dummy <- alpha.create(party, new Dummy(party))
tree <- alpha.exercise(party, dummy.exerciseDummyChoice1())
_ <- synchronize(alpha, beta)
failure <- beta
@ -71,7 +72,7 @@ class TransactionServiceQueryIT extends LedgerTestSuite {
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
for {
dummy <- ledger.create(party, Dummy(party))
dummy <- ledger.create(party, new Dummy(party))
transaction <- ledger.exerciseForFlatTransaction(party, dummy.exerciseDummyChoice1())
byId <- ledger.flatTransactionById(transaction.transactionId, party)
} yield {
@ -85,7 +86,7 @@ class TransactionServiceQueryIT extends LedgerTestSuite {
allocate(TwoParties),
)(implicit ec => { case Participants(Participant(ledger, party, intruder)) =>
for {
dummy <- ledger.create(party, Dummy(party))
dummy <- ledger.create(party, new Dummy(party))
tree <- ledger.exercise(party, dummy.exerciseDummyChoice1())
failure <- ledger
.flatTransactionById(tree.transactionId, intruder)
@ -123,7 +124,7 @@ class TransactionServiceQueryIT extends LedgerTestSuite {
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
for {
dummy <- ledger.create(party, Dummy(party))
dummy <- ledger.create(party, new Dummy(party))
tree <- ledger.exercise(party, dummy.exerciseDummyChoice1())
byId <- ledger.transactionTreeByEventId(tree.rootEventIds.head, party)
} yield {
@ -138,7 +139,7 @@ class TransactionServiceQueryIT extends LedgerTestSuite {
timeoutScale = 2.0,
)(implicit ec => { case Participants(Participant(alpha, party), Participant(beta, intruder)) =>
for {
dummy <- alpha.create(party, Dummy(party))
dummy <- alpha.create(party, new Dummy(party))
tree <- alpha.exercise(party, dummy.exerciseDummyChoice1())
_ <- synchronize(alpha, beta)
failure <- beta
@ -177,7 +178,7 @@ class TransactionServiceQueryIT extends LedgerTestSuite {
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
for {
dummy <- ledger.create(party, Dummy(party))
dummy <- ledger.create(party, new Dummy(party))
transaction <- ledger.exerciseForFlatTransaction(party, dummy.exerciseDummyChoice1())
event = transaction.events.head.event
eventId = event.archived.map(_.eventId).get
@ -193,7 +194,7 @@ class TransactionServiceQueryIT extends LedgerTestSuite {
allocate(TwoParties),
)(implicit ec => { case Participants(Participant(ledger, party, intruder)) =>
for {
dummy <- ledger.create(party, Dummy(party))
dummy <- ledger.create(party, new Dummy(party))
tree <- ledger.exercise(party, dummy.exerciseDummyChoice1())
failure <- ledger
.flatTransactionByEventId(tree.rootEventIds.head, intruder)

View File

@ -7,23 +7,25 @@ import com.daml.ledger.api.testtool.infrastructure.Allocation._
import com.daml.ledger.api.testtool.infrastructure.Assertions._
import com.daml.ledger.api.testtool.infrastructure.LedgerTestSuite
import com.daml.ledger.api.testtool.infrastructure.TransactionHelpers._
import com.daml.ledger.test.model.Test._
import scalaz.Tag
import com.daml.ledger.test.java.model.test._
import scala.collection.immutable.Seq
import scala.concurrent.Future
import scala.jdk.CollectionConverters._
class TransactionServiceStakeholdersIT extends LedgerTestSuite {
import CompanionImplicits._
test("TXStakeholders", "Expose the correct stakeholders", allocate(SingleParty, SingleParty))(
implicit ec => {
case Participants(Participant(alpha @ _, receiver), Participant(beta, giver)) =>
for {
_ <- beta.create(giver, CallablePayout(giver, receiver))
_ <- beta.create(giver, new CallablePayout(giver, receiver))
transactions <- beta.flatTransactions(giver, receiver)
} yield {
val contract = assertSingleton("Stakeholders", transactions.flatMap(createdEvents))
assertEquals("Signatories", contract.signatories, Seq(Tag.unwrap(giver)))
assertEquals("Observers", contract.observers, Seq(Tag.unwrap(receiver)))
assertEquals("Signatories", contract.signatories, Seq(giver.getValue))
assertEquals("Observers", contract.observers, Seq(receiver.getValue))
}
}
)
@ -34,19 +36,19 @@ class TransactionServiceStakeholdersIT extends LedgerTestSuite {
allocate(TwoParties),
)(implicit ec => { case Participants(Participant(ledger, alice, bob)) =>
for {
_ <- ledger.create(alice, WithObservers(alice, Seq(alice, bob)))
_ <- ledger.create(alice, new WithObservers(alice, Seq(alice, bob).map(_.getValue).asJava))
flatTx <- ledger.flatTransactions(alice).flatMap(fs => Future(fs.head))
flatWo <- Future(createdEvents(flatTx).head)
treeTx <- ledger.transactionTrees(alice).flatMap(fs => Future(fs.head))
treeWo <- Future(createdEvents(treeTx).head)
} yield {
assert(
flatWo.observers == Seq(bob),
s"Expected observers to only contain $bob, but received ${flatWo.observers}",
flatWo.observers == Seq(bob.getValue),
s"Expected observers to only contain ${bob.getValue}, but received ${flatWo.observers}",
)
assert(
treeWo.observers == Seq(bob),
s"Expected observers to only contain $bob, but received ${treeWo.observers}",
treeWo.observers == Seq(bob.getValue),
s"Expected observers to only contain ${bob.getValue}, but received ${treeWo.observers}",
)
}
})
@ -57,12 +59,12 @@ class TransactionServiceStakeholdersIT extends LedgerTestSuite {
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
// Create command with transient contract
val createAndExercise = Dummy(party).createAnd.exerciseArchive().command
val createAndExercise = new Dummy(party).createAnd.exerciseArchive().commands
for {
_ <- ledger.submitAndWait(ledger.submitAndWaitRequest(party, createAndExercise))
emptyFlatTx <- ledger.flatTransactions(party)
emptyFlatTxByTemplateId <- ledger.flatTransactionsByTemplateId(Dummy.id, party)
emptyFlatTxByTemplateId <- ledger.flatTransactionsByTemplateId(Dummy.TEMPLATE_ID, party)
} yield {
assert(
emptyFlatTx.length == 1,
@ -90,7 +92,9 @@ class TransactionServiceStakeholdersIT extends LedgerTestSuite {
)(implicit ec => { case Participants(Participant(ledger, submitter, observer)) =>
// Create command with transient contract
val createAndExerciseWithObservers =
WithObservers(submitter, List(observer)).createAnd.exerciseArchive().command
new WithObservers(submitter, List(observer.getValue).asJava).createAnd
.exerciseArchive()
.commands
for {
// The in-memory fan-out serves at least N-1 transaction responses from a specific query window
// Then, submit 2 requests to ensure that a transaction from the in-memory fan-out would be forwarded.
@ -103,7 +107,10 @@ class TransactionServiceStakeholdersIT extends LedgerTestSuite {
// `observer` is just a stakeholder on the contract created by `submitter`
// but it should not see the completion/flat transaction if it has only transient events.
emptyFlatTx <- ledger.flatTransactions(observer)
emptyFlatTxByTemplateId <- ledger.flatTransactionsByTemplateId(WithObservers.id, observer)
emptyFlatTxByTemplateId <- ledger.flatTransactionsByTemplateId(
WithObservers.TEMPLATE_ID,
observer,
)
} yield {
assert(emptyFlatTx.isEmpty, s"No transaction expected but got $emptyFlatTx instead")
assert(

View File

@ -8,13 +8,15 @@ import com.daml.ledger.api.testtool.infrastructure.Allocation._
import com.daml.ledger.api.testtool.infrastructure.Assertions._
import com.daml.ledger.api.testtool.infrastructure.LedgerTestSuite
import com.daml.ledger.api.testtool.infrastructure.TransactionHelpers._
import com.daml.ledger.test.model.Test._
import scalaz.Tag
import com.daml.ledger.test.java.model.test._
import scala.collection.immutable.Seq
import scala.concurrent.Future
import scala.jdk.CollectionConverters._
class TransactionServiceStreamsIT extends LedgerTestSuite {
import CompanionImplicits._
test(
"TXBeginToBegin",
"An empty stream should be served when getting transactions from and to the beginning of the ledger",
@ -55,7 +57,7 @@ class TransactionServiceStreamsIT extends LedgerTestSuite {
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
for {
_ <- ledger.create(party, Dummy(party))
_ <- ledger.create(party, new Dummy(party))
request = ledger.getTransactionsRequest(ledger.transactionFilter(Seq(party)))
endToEnd = request.update(_.begin := ledger.end, _.end := ledger.end)
transactions <- ledger.flatTransactions(endToEnd)
@ -73,7 +75,7 @@ class TransactionServiceStreamsIT extends LedgerTestSuite {
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
for {
_ <- ledger.create(party, Dummy(party))
_ <- ledger.create(party, new Dummy(party))
futureOffset <- ledger.offsetBeyondLedgerEnd()
request = ledger.getTransactionsRequest(ledger.transactionFilter(Seq(party)))
beyondEnd = request.update(_.begin := futureOffset, _.optionalEnd := None)
@ -93,7 +95,7 @@ class TransactionServiceStreamsIT extends LedgerTestSuite {
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
for {
_ <- ledger.create(party, Dummy(party))
_ <- ledger.create(party, new Dummy(party))
futureOffset <- ledger.offsetBeyondLedgerEnd()
request = ledger.getTransactionsRequest(ledger.transactionFilter(Seq(party)))
beyondEnd = request.update(_.begin := futureOffset, _.optionalEnd := None)
@ -116,7 +118,7 @@ class TransactionServiceStreamsIT extends LedgerTestSuite {
val transactionsToRead = 10
for {
dummies <- Future.sequence(
Vector.fill(transactionsToSubmit)(ledger.create(party, Dummy(party)))
Vector.fill(transactionsToSubmit)(ledger.create(party, new Dummy(party)))
)
transactions <- ledger.flatTransactions(transactionsToRead, party)
} yield {
@ -140,7 +142,7 @@ class TransactionServiceStreamsIT extends LedgerTestSuite {
val treesToRead = 10
for {
dummies <- Future.sequence(
Vector.fill(transactionsToSubmit)(ledger.create(party, Dummy(party)))
Vector.fill(transactionsToSubmit)(ledger.create(party, new Dummy(party)))
)
trees <- ledger.transactionTrees(treesToRead, party)
} yield {
@ -163,7 +165,9 @@ class TransactionServiceStreamsIT extends LedgerTestSuite {
val transactionsToSubmit = 14
val transactionsFuture = ledger.flatTransactions(party)
for {
_ <- Future.sequence(Vector.fill(transactionsToSubmit)(ledger.create(party, Dummy(party))))
_ <- Future.sequence(
Vector.fill(transactionsToSubmit)(ledger.create(party, new Dummy(party)))
)
_ <- transactionsFuture
} yield {
// doing nothing: we are just checking that `transactionsFuture` completes successfully
@ -178,7 +182,9 @@ class TransactionServiceStreamsIT extends LedgerTestSuite {
val transactionsToSubmit = 14
val transactionsFuture = ledger.transactionTrees(party)
for {
_ <- Future.sequence(Vector.fill(transactionsToSubmit)(ledger.create(party, Dummy(party))))
_ <- Future.sequence(
Vector.fill(transactionsToSubmit)(ledger.create(party, new Dummy(party)))
)
_ <- transactionsFuture
} yield {
// doing nothing: we are just checking that `transactionsFuture` completes successfully
@ -190,18 +196,19 @@ class TransactionServiceStreamsIT extends LedgerTestSuite {
"The transaction service should correctly filter by template identifier",
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
val filterBy = Dummy.id
val filterBy = Dummy.TEMPLATE_ID
val create = ledger.submitAndWaitRequest(
party,
Dummy(party).create.command,
DummyFactory(party).create.command,
(new Dummy(party).create.commands.asScala ++ new DummyFactory(
party
).create.commands.asScala).asJava,
)
for {
_ <- ledger.submitAndWait(create)
transactions <- ledger.flatTransactionsByTemplateId(filterBy, party)
} yield {
val contract = assertSingleton("FilterByTemplate", transactions.flatMap(createdEvents))
assertEquals("FilterByTemplate", contract.getTemplateId, Tag.unwrap(filterBy))
assertEquals("FilterByTemplate", contract.getTemplateId, filterBy.toV1)
}
})
}

View File

@ -7,11 +7,13 @@ import com.daml.error.definitions.LedgerApiErrors
import com.daml.ledger.api.testtool.infrastructure.Allocation._
import com.daml.ledger.api.testtool.infrastructure.Assertions._
import com.daml.ledger.api.testtool.infrastructure.LedgerTestSuite
import com.daml.ledger.test.model.Test._
import com.daml.ledger.test.java.model.test._
import scala.collection.immutable.Seq
class TransactionServiceValidationIT extends LedgerTestSuite {
import CompanionImplicits._
test(
"TXRejectEmptyFilter",
"A query with an empty transaction filter should be rejected with an INVALID_ARGUMENT status",
@ -39,7 +41,7 @@ class TransactionServiceValidationIT extends LedgerTestSuite {
)(implicit ec => { case Participants(Participant(ledger, party)) =>
for {
earlier <- ledger.currentEnd()
_ <- ledger.create(party, Dummy(party))
_ <- ledger.create(party, new Dummy(party))
later <- ledger.currentEnd()
request = ledger.getTransactionsRequest(ledger.transactionFilter(Seq(party)))
invalidRequest = request.update(_.begin := later, _.end := earlier)

View File

@ -13,26 +13,34 @@ import com.daml.ledger.api.testtool.suites.v1_8.TransactionServiceVisibilityIT._
import com.daml.ledger.api.v1.event.Event.Event
import com.daml.ledger.api.v1.transaction.TreeEvent.Kind.Exercised
import com.daml.ledger.api.v1.transaction.{Transaction, TransactionTree, TreeEvent}
import com.daml.ledger.client.binding
import com.daml.ledger.client.binding.Primitive
import com.daml.ledger.test.model.Iou.Iou
import com.daml.ledger.test.model.Iou.Iou._
import com.daml.ledger.test.model.Iou.IouTransfer._
import com.daml.ledger.test.model.IouTrade.IouTrade
import com.daml.ledger.test.model.IouTrade.IouTrade._
import com.daml.ledger.test.model.Test._
import com.daml.ledger.api.v1.value.Record
import com.daml.ledger.javaapi.data.Party
import com.daml.ledger.javaapi.data.codegen.ContractCompanion
import com.daml.ledger.test.java.model.iou.{Iou, IouTransfer}
import com.daml.ledger.test.java.model.ioutrade.IouTrade
import com.daml.ledger.test.java.model.test._
import com.daml.lf.ledger.EventId
import com.daml.test.evidence.tag.EvidenceTag
import com.daml.test.evidence.tag.Security.SecurityTest
import com.daml.test.evidence.tag.Security.SecurityTest.Property.Privacy
import scala.annotation.nowarn
import scala.collection.immutable.Seq
import scala.collection.mutable
import scala.concurrent.{ExecutionContext, Future}
import scala.jdk.CollectionConverters._
class TransactionServiceVisibilityIT extends LedgerTestSuite {
import BigDecimalImplicits._
import CompanionImplicits._
implicit val iouTransferCompanion
: ContractCompanion.WithoutKey[IouTransfer.Contract, IouTransfer.ContractId, IouTransfer] =
IouTransfer.COMPANION
implicit val iouTradeCompanion
: ContractCompanion.WithoutKey[IouTrade.Contract, IouTrade.ContractId, IouTrade] =
IouTrade.COMPANION
// quadruple the eventually wait duration compared to default to avoid database timeouts
// when running against Oracle in enterprise mode
def eventually[A](
@ -66,27 +74,58 @@ class TransactionServiceVisibilityIT extends LedgerTestSuite {
Participant(delta, dkk_bank),
) =>
for {
gbpIouIssue <- alpha.create(gbp_bank, Iou(gbp_bank, gbp_bank, "GBP", 100, Nil))
gbpIouIssue <- alpha.create(
gbp_bank,
new Iou(gbp_bank, gbp_bank, "GBP", 100.toBigDecimal, Nil.asJava),
)
gbpTransfer <-
alpha.exerciseAndGetContract(gbp_bank, gbpIouIssue.exerciseIou_Transfer(alice))
dkkIouIssue <- delta.create(dkk_bank, Iou(dkk_bank, dkk_bank, "DKK", 110, Nil))
alpha.exerciseAndGetContract[IouTransfer.ContractId, IouTransfer](
gbp_bank,
gbpIouIssue.exerciseIou_Transfer(alice),
)
dkkIouIssue <- delta.create(
dkk_bank,
new Iou(dkk_bank, dkk_bank, "DKK", 110.toBigDecimal, Nil.asJava),
)
dkkTransfer <-
delta.exerciseAndGetContract(dkk_bank, dkkIouIssue.exerciseIou_Transfer(bob))
delta.exerciseAndGetContract[IouTransfer.ContractId, IouTransfer](
dkk_bank,
dkkIouIssue.exerciseIou_Transfer(bob),
)
aliceIou1 <- eventually("exerciseIouTransfer_Accept") {
alpha.exerciseAndGetContract(alice, gbpTransfer.exerciseIouTransfer_Accept())
alpha.exerciseAndGetContract[Iou.ContractId, Iou](
alice,
gbpTransfer.exerciseIouTransfer_Accept(),
)
}
aliceIou <- eventually("exerciseIou_AddObserver") {
alpha.exerciseAndGetContract(alice, aliceIou1.exerciseIou_AddObserver(bob))
alpha.exerciseAndGetContract[Iou.ContractId, Iou](
alice,
aliceIou1.exerciseIou_AddObserver(bob),
)
}
bobIou <- eventually("exerciseIouTransfer_Accept") {
beta.exerciseAndGetContract(bob, dkkTransfer.exerciseIouTransfer_Accept())
beta.exerciseAndGetContract[Iou.ContractId, Iou](
bob,
dkkTransfer.exerciseIouTransfer_Accept(),
)
}
trade <- eventually("create") {
alpha.create(
alice,
IouTrade(alice, bob, aliceIou, gbp_bank, "GBP", 100, dkk_bank, "DKK", 110),
new IouTrade(
alice,
bob,
aliceIou,
gbp_bank,
"GBP",
100.toBigDecimal,
dkk_bank,
"DKK",
110.toBigDecimal,
),
)
}
tree <- eventually("exerciseIouTrade_Accept") {
@ -170,27 +209,58 @@ class TransactionServiceVisibilityIT extends LedgerTestSuite {
Participant(delta, dkk_bank),
) =>
for {
gbpIouIssue <- alpha.create(gbp_bank, Iou(gbp_bank, gbp_bank, "GBP", 100, Nil))
gbpIouIssue <- alpha.create(
gbp_bank,
new Iou(gbp_bank, gbp_bank, "GBP", 100.toBigDecimal, Nil.asJava),
)
gbpTransfer <-
alpha.exerciseAndGetContract(gbp_bank, gbpIouIssue.exerciseIou_Transfer(alice))
dkkIouIssue <- delta.create(dkk_bank, Iou(dkk_bank, dkk_bank, "DKK", 110, Nil))
alpha.exerciseAndGetContract[IouTransfer.ContractId, IouTransfer](
gbp_bank,
gbpIouIssue.exerciseIou_Transfer(alice),
)
dkkIouIssue <- delta.create(
dkk_bank,
new Iou(dkk_bank, dkk_bank, "DKK", 110.toBigDecimal, Nil.asJava),
)
dkkTransfer <-
delta.exerciseAndGetContract(dkk_bank, dkkIouIssue.exerciseIou_Transfer(bob))
delta.exerciseAndGetContract[IouTransfer.ContractId, IouTransfer](
dkk_bank,
dkkIouIssue.exerciseIou_Transfer(bob),
)
aliceIou1 <- eventually("exerciseIouTransfer_Accept") {
alpha.exerciseAndGetContract(alice, gbpTransfer.exerciseIouTransfer_Accept())
alpha.exerciseAndGetContract[Iou.ContractId, Iou](
alice,
gbpTransfer.exerciseIouTransfer_Accept(),
)
}
aliceIou <- eventually("exerciseIou_AddObserver") {
alpha.exerciseAndGetContract(alice, aliceIou1.exerciseIou_AddObserver(bob))
alpha.exerciseAndGetContract[Iou.ContractId, Iou](
alice,
aliceIou1.exerciseIou_AddObserver(bob),
)
}
bobIou <- eventually("exerciseIouTransfer_Accept") {
beta.exerciseAndGetContract(bob, dkkTransfer.exerciseIouTransfer_Accept())
beta.exerciseAndGetContract[Iou.ContractId, Iou](
bob,
dkkTransfer.exerciseIouTransfer_Accept(),
)
}
trade <- eventually("create") {
alpha.create(
alice,
IouTrade(alice, bob, aliceIou, gbp_bank, "GBP", 100, dkk_bank, "DKK", 110),
new IouTrade(
alice,
bob,
aliceIou,
gbp_bank,
"GBP",
100.toBigDecimal,
dkk_bank,
"DKK",
110.toBigDecimal,
),
)
}
tree <- eventually("exerciseIouTrade_Accept") {
@ -268,7 +338,7 @@ class TransactionServiceVisibilityIT extends LedgerTestSuite {
),
)(implicit ec => { case Participants(Participant(alpha, alice), Participant(_, bob)) =>
for {
_ <- alpha.create(alice, Dummy(alice))
_ <- alpha.create(alice, new Dummy(alice))
bobsView <- alpha.flatTransactions(bob)
} yield {
assert(
@ -292,7 +362,7 @@ class TransactionServiceVisibilityIT extends LedgerTestSuite {
for {
(id, _) <- alpha.createAndGetTransactionId(
submitter,
AgreementFactory(listener, submitter),
new AgreementFactory(listener, submitter),
)
_ <- synchronize(alpha, beta)
tree <- beta.transactionTreeById(id, listener)
@ -331,7 +401,7 @@ class TransactionServiceVisibilityIT extends LedgerTestSuite {
for {
(id, _) <- alpha.createAndGetTransactionId(
submitter,
AgreementFactory(listener, submitter),
new AgreementFactory(listener, submitter),
)
_ <- synchronize(alpha, beta)
flatTx <- beta.flatTransactionById(id, listener)
@ -366,8 +436,8 @@ class TransactionServiceVisibilityIT extends LedgerTestSuite {
"Transaction with a create event is not disclosed to non-chosen branching signatory",
),
)(implicit ec => { case Participants(Participant(alpha, alice), Participant(beta, bob)) =>
val template = BranchingSignatories(whichSign = false, signTrue = alice, signFalse = bob)
val create = beta.submitAndWaitRequest(bob, template.create.command)
val template = new BranchingSignatories(false, alice, bob)
val create = beta.submitAndWaitRequest(bob, template.create.commands)
for {
transactionResponse <- beta.submitAndWaitForTransaction(create)
_ <- synchronize(alpha, beta)
@ -395,10 +465,11 @@ class TransactionServiceVisibilityIT extends LedgerTestSuite {
happyCase = "Transaction with a create event is disclosed to chosen branching controller",
),
)(implicit ec => { case Participants(Participant(alpha, alice), Participant(beta, bob, eve)) =>
import ClearIdsImplicits._
val template =
BranchingControllers(giver = alice, whichCtrl = true, ctrlTrue = bob, ctrlFalse = eve)
new BranchingControllers(alice, true, bob, eve)
for {
_ <- alpha.create(alice, template)
_ <- alpha.create(alice, template)(BranchingControllers.COMPANION)
_ <- eventually("flatTransactions") {
for {
aliceView <- alpha.flatTransactions(alice)
@ -409,15 +480,15 @@ class TransactionServiceVisibilityIT extends LedgerTestSuite {
assertSingleton("Alice should see one transaction", aliceView.flatMap(createdEvents))
assertEquals(
"Alice arguments do not match",
aliceCreate.getCreateArguments,
template.arguments,
aliceCreate.getCreateArguments.clearValueIds,
Record.fromJavaProto(template.toValue.toProtoRecord),
)
val bobCreate =
assertSingleton("Bob should see one transaction", bobView.flatMap(createdEvents))
assertEquals(
"Bob arguments do not match",
bobCreate.getCreateArguments,
template.arguments,
bobCreate.getCreateArguments.clearValueIds,
Record.fromJavaProto(template.toValue.toProtoRecord),
)
assert(evesView.isEmpty, "Eve should not see any contract")
}
@ -438,8 +509,8 @@ class TransactionServiceVisibilityIT extends LedgerTestSuite {
),
)(implicit ec => { case Participants(Participant(alpha, alice), Participant(beta, bob, eve)) =>
val template =
BranchingControllers(giver = alice, whichCtrl = false, ctrlTrue = bob, ctrlFalse = eve)
val create = alpha.submitAndWaitRequest(alice, template.create.command)
new BranchingControllers(alice, false, bob, eve)
val create = alpha.submitAndWaitRequest(alice, template.create.commands)
for {
transactionResponse <- alpha.submitAndWaitForTransaction(create)
_ <- synchronize(alpha, beta)
@ -464,8 +535,8 @@ class TransactionServiceVisibilityIT extends LedgerTestSuite {
),
)(implicit ec => {
case Participants(Participant(alpha, alice), Participant(beta, observers @ _*)) =>
val template = WithObservers(alice, Primitive.List(observers: _*))
val create = alpha.submitAndWaitRequest(alice, template.create.command)
val template = new WithObservers(alice, observers.map(_.getValue).asJava)
val create = alpha.submitAndWaitRequest(alice, template.create.commands)
for {
transactionId <- alpha.submitAndWaitForTransactionId(create).map(_.transactionId)
_ <- eventually("flatTransactions") {
@ -492,20 +563,38 @@ class TransactionServiceVisibilityIT extends LedgerTestSuite {
),
)(implicit ec => { case Participants(Participant(ledger, bank, alice, bob)) =>
for {
gbpIouIssue <- ledger.create(bank, Iou(bank, bank, "GBP", 100, Nil))
gbpTransfer <- ledger.exerciseAndGetContract(
gbpIouIssue <- ledger.create(bank, new Iou(bank, bank, "GBP", 100.toBigDecimal, Nil.asJava))
gbpTransfer <- ledger.exerciseAndGetContract[IouTransfer.ContractId, IouTransfer](
bank,
gbpIouIssue.exerciseIou_Transfer(alice),
)
dkkIouIssue <- ledger.create(bank, Iou(bank, bank, "DKK", 110, Nil))
dkkTransfer <- ledger.exerciseAndGetContract(bank, dkkIouIssue.exerciseIou_Transfer(bob))
aliceIou1 <- ledger.exerciseAndGetContract(alice, gbpTransfer.exerciseIouTransfer_Accept())
aliceIou <- ledger.exerciseAndGetContract(alice, aliceIou1.exerciseIou_AddObserver(bob))
bobIou <- ledger.exerciseAndGetContract(bob, dkkTransfer.exerciseIouTransfer_Accept())
dkkIouIssue <- ledger.create(bank, new Iou(bank, bank, "DKK", 110.toBigDecimal, Nil.asJava))
dkkTransfer <- ledger.exerciseAndGetContract[IouTransfer.ContractId, IouTransfer](
bank,
dkkIouIssue.exerciseIou_Transfer(bob),
)
aliceIou1 <- ledger.exerciseAndGetContract[Iou.ContractId, Iou](
alice,
gbpTransfer.exerciseIouTransfer_Accept(),
)
aliceIou <- ledger
.exerciseAndGetContract[Iou.ContractId, Iou](alice, aliceIou1.exerciseIou_AddObserver(bob))
bobIou <- ledger
.exerciseAndGetContract[Iou.ContractId, Iou](bob, dkkTransfer.exerciseIouTransfer_Accept())
trade <- ledger.create(
alice,
IouTrade(alice, bob, aliceIou, bank, "GBP", 100, bank, "DKK", 110),
new IouTrade(
alice,
bob,
aliceIou,
bank,
"GBP",
100.toBigDecimal,
bank,
"DKK",
110.toBigDecimal,
),
)
tree <- ledger.exercise(bob, trade.exerciseIouTrade_Accept(bobIou))
@ -521,17 +610,19 @@ class TransactionServiceVisibilityIT extends LedgerTestSuite {
s"Expected 2 new IOUs created, found: ${newIouList.length}",
)
@nowarn("cat=lint-infer-any")
val newAliceIou = newIouList
.find(iou => iou.signatories.contains(alice) && iou.signatories.contains(bank))
.find(iou =>
iou.signatories.contains(alice.getValue) && iou.signatories.contains(bank.getValue)
)
.map(_.contractId)
.getOrElse {
fail(s"Not found an IOU owned by $alice")
}
@nowarn("cat=lint-infer-any")
val newBobIou = newIouList
.find(iou => iou.signatories.contains(bob) && iou.signatories.contains(bank))
.find(iou =>
iou.signatories.contains(bob.getValue) && iou.signatories.contains(bank.getValue)
)
.map(_.contractId)
.getOrElse {
fail(s"Not found an IOU owned by $bob")
@ -566,10 +657,15 @@ class TransactionServiceVisibilityIT extends LedgerTestSuite {
),
)(implicit ec => { case Participants(Participant(ledger, bank, alice, bob)) =>
for {
iouIssue <- ledger.create(bank, Iou(bank, bank, "GBP", 100, Nil))
transfer <- ledger.exerciseAndGetContract(bank, iouIssue.exerciseIou_Transfer(alice))
aliceIou <- ledger.exerciseAndGetContract(alice, transfer.exerciseIouTransfer_Accept())
_ <- ledger.exerciseAndGetContract(alice, aliceIou.exerciseIou_AddObserver(bob))
iouIssue <- ledger.create(bank, new Iou(bank, bank, "GBP", 100.toBigDecimal, Nil.asJava))
transfer <- ledger.exerciseAndGetContract[IouTransfer.ContractId, IouTransfer](
bank,
iouIssue.exerciseIou_Transfer(alice),
)
aliceIou <- ledger
.exerciseAndGetContract[Iou.ContractId, Iou](alice, transfer.exerciseIouTransfer_Accept())
_ <- ledger
.exerciseAndGetContract[Iou.ContractId, Iou](alice, aliceIou.exerciseIou_AddObserver(bob))
aliceFlatTransactions <- ledger.flatTransactions(alice)
bobFlatTransactions <- ledger.flatTransactions(bob)
aliceBankFlatTransactions <- ledger.flatTransactions(alice, bank)
@ -598,10 +694,15 @@ class TransactionServiceVisibilityIT extends LedgerTestSuite {
),
)(implicit ec => { case Participants(Participant(ledger, bank, alice, bob)) =>
for {
iouIssue <- ledger.create(bank, Iou(bank, bank, "GBP", 100, Nil))
transfer <- ledger.exerciseAndGetContract(bank, iouIssue.exerciseIou_Transfer(alice))
aliceIou <- ledger.exerciseAndGetContract(alice, transfer.exerciseIouTransfer_Accept())
_ <- ledger.exerciseAndGetContract(alice, aliceIou.exerciseIou_AddObserver(bob))
iouIssue <- ledger.create(bank, new Iou(bank, bank, "GBP", 100.toBigDecimal, Nil.asJava))
transfer <- ledger.exerciseAndGetContract[IouTransfer.ContractId, IouTransfer](
bank,
iouIssue.exerciseIou_Transfer(alice),
)(IouTransfer.COMPANION)
aliceIou <- ledger
.exerciseAndGetContract[Iou.ContractId, Iou](alice, transfer.exerciseIouTransfer_Accept())
_ <- ledger
.exerciseAndGetContract[Iou.ContractId, Iou](alice, aliceIou.exerciseIou_AddObserver(bob))
aliceTransactionTrees <- ledger.transactionTrees(alice)
bobTransactionTrees <- ledger.transactionTrees(bob)
aliceBankTransactionTrees <- ledger.transactionTrees(alice, bank)
@ -628,9 +729,9 @@ class TransactionServiceVisibilityIT extends LedgerTestSuite {
object TransactionServiceVisibilityIT {
private def onlyRequestingPartiesAsWitnesses(
allWitnesses: Set[String],
requestingParties: binding.Primitive.Party*
requestingParties: Party*
)(msg: String): Unit = {
val nonRequestingWitnesses = allWitnesses.diff(requestingParties.map(_.toString).toSet)
val nonRequestingWitnesses = allWitnesses.diff(requestingParties.map(_.getValue).toSet)
assert(
nonRequestingWitnesses.isEmpty,
s"$msg: ${nonRequestingWitnesses.mkString("[", ",", "]")}",

View File

@ -32,9 +32,8 @@ import com.daml.ledger.api.v1.admin.user_management_service.{
Right => Permission,
}
import com.daml.ledger.api.v1.admin.{user_management_service => proto}
import com.daml.ledger.client.binding.Primitive
import com.daml.ledger.javaapi.data.Party
import io.grpc.{Status, StatusRuntimeException}
import scalaz.Tag
import scala.concurrent.{ExecutionContext, Future}
import scala.util.{Failure, Success}
@ -327,8 +326,8 @@ final class UserManagementServiceIT extends UserManagementServiceITBase {
)
}
def createCanActAs(party: Primitive.Party) =
Permission(Permission.Kind.CanActAs(Permission.CanActAs(Tag.unwrap(party))))
def createCanActAs(party: Party) =
Permission(Permission.Kind.CanActAs(Permission.CanActAs(party)))
def allocateParty(id: Int) =
ledger.allocateParty(Some(s"acting-party-$id"))
@ -1123,10 +1122,10 @@ final class UserManagementServiceIT extends UserManagementServiceITBase {
reading1 <- ledger.allocateParty(Some(s"reading-party-1-$suffix"))
reading2 <- ledger.allocateParty(Some(s"reading-party-2-$suffix"))
} yield UserManagementServiceIT.Parties(
Tag.unwrap(acting1),
Tag.unwrap(acting2),
Tag.unwrap(reading1),
Tag.unwrap(reading2),
acting1,
acting2,
reading1,
reading2,
)
}
}

View File

@ -6,7 +6,7 @@ package com.daml.ledger.api.testtool.suites.v1_8
import com.daml.ledger.api.testtool.infrastructure.Allocation._
import com.daml.ledger.api.testtool.infrastructure.Assertions._
import com.daml.ledger.api.testtool.infrastructure.LedgerTestSuite
import com.daml.ledger.test.model.Test.DummyWithAnnotation
import com.daml.ledger.test.java.model.test.DummyWithAnnotation
import scala.concurrent.Future
import scala.util.Random
@ -31,7 +31,8 @@ final class ValueLimitsIT extends LedgerTestSuite {
.submitAndWaitRequest(
actAs = parties.toList,
readAs = parties.toList,
commands = DummyWithAnnotation(parties.head, "First submission").create.command,
commands =
new DummyWithAnnotation(parties.head.getValue, "First submission").create.commands,
)
_ <- ledger.submitAndWait(request)
contracts <- ledger.activeContracts(parties.head)

View File

@ -4,10 +4,7 @@ package com.daml.ledger.api.testtool.suites.v1_8
import com.daml.ledger.api.testtool.infrastructure.Allocation._
import com.daml.ledger.api.testtool.infrastructure.LedgerTestSuite
import com.daml.ledger.test.model.Test.DivulgeWitnesses._
import com.daml.ledger.test.model.Test.Witnesses._
import com.daml.ledger.test.model.Test.{DivulgeWitnesses, Witnesses => WitnessesTemplate}
import scalaz.Tag
import com.daml.ledger.test.java.model.test.{DivulgeWitnesses, Witnesses}
final class WitnessesIT extends LedgerTestSuite {
test(
@ -17,10 +14,11 @@ final class WitnessesIT extends LedgerTestSuite {
)(implicit ec => { case Participants(Participant(ledger, alice, bob, charlie)) =>
for {
// Create the Witnesses contract as Alice and get the resulting transaction as seen by all parties
(witnessesTransactionId, witnesses) <- ledger.createAndGetTransactionId(
alice,
WitnessesTemplate(alice, bob, charlie),
)
(witnessesTransactionId, witnesses) <- ledger
.createAndGetTransactionId(
alice,
new Witnesses(alice, bob, charlie),
)(Witnesses.COMPANION)
witnessesTransaction <- ledger.transactionTreeById(
witnessesTransactionId,
alice,
@ -32,7 +30,9 @@ final class WitnessesIT extends LedgerTestSuite {
// Such contract is divulged by creating a DivulgeWitness with Charlie as a signatory and exercising
// a choice as Alice that causes divulgence (in this case, the Witnesses instance previously
// created is fetched as part of the transaction).
divulgeWitness <- ledger.create(charlie, DivulgeWitnesses(alice, charlie))
divulgeWitness <- ledger.create(charlie, new DivulgeWitnesses(alice, charlie))(
DivulgeWitnesses.COMPANION
)
_ <- ledger.exercise(alice, divulgeWitness.exerciseDivulge(witnesses))
// A non-consuming choice is exercised with the expectation
@ -63,7 +63,7 @@ final class WitnessesIT extends LedgerTestSuite {
s"The event in the transaction for creating the Witness should be a CreatedEvent, but was ${creationEvent.kind}",
)
val expectedWitnessesOfCreation = Tag.unsubst(Seq(alice, bob)).sorted
val expectedWitnessesOfCreation = Seq(alice, bob).map(_.getValue).sorted
assert(
creationEvent.getCreated.witnessParties.sorted == expectedWitnessesOfCreation,
s"The parties for witnessing the CreatedEvent should be $expectedWitnessesOfCreation, but were ${creationEvent.getCreated.witnessParties}",
@ -78,7 +78,7 @@ final class WitnessesIT extends LedgerTestSuite {
s"The event in the transaction for exercising the non-consuming choice should be an ExercisedEvent, but was ${nonConsumingEvent.kind}",
)
val expectedWitnessesOfNonConsumingChoice = Tag.unsubst(Seq(alice, charlie)).sorted
val expectedWitnessesOfNonConsumingChoice = Seq(alice, charlie).map(_.getValue).sorted
assert(
nonConsumingEvent.getExercised.witnessParties.sorted == expectedWitnessesOfNonConsumingChoice,
s"The parties for witnessing the non-consuming ExercisedEvent should be $expectedWitnessesOfNonConsumingChoice, but were ${nonConsumingEvent.getCreated.witnessParties}",
@ -93,7 +93,7 @@ final class WitnessesIT extends LedgerTestSuite {
consumingEvent.kind.isExercised,
s"The event in the transaction for exercising the consuming choice should be an ExercisedEvent, but was ${consumingEvent.kind}",
)
val expectedWitnessesOfConsumingChoice = Tag.unsubst(Seq(alice, bob, charlie)).sorted
val expectedWitnessesOfConsumingChoice = Seq(alice, bob, charlie).map(_.getValue).sorted
assert(
consumingEvent.getExercised.witnessParties.sorted == expectedWitnessesOfConsumingChoice,
s"The parties for witnessing the consuming ExercisedEvent should be $expectedWitnessesOfConsumingChoice, but were ${consumingEvent.getCreated.witnessParties}",

View File

@ -7,17 +7,18 @@ import com.daml.error.definitions.LedgerApiErrors
import com.daml.ledger.api.testtool.infrastructure.Allocation._
import com.daml.ledger.api.testtool.infrastructure.Assertions._
import com.daml.ledger.api.testtool.infrastructure.LedgerTestSuite
import com.daml.ledger.client.binding.Primitive
import com.daml.ledger.test.model.Test.Delegation._
import com.daml.ledger.test.model.Test.DummyWithParam._
import com.daml.ledger.test.model.Test.{Delegated, Delegation, Dummy, DummyWithParam}
import com.daml.ledger.test.java.model.test.{Delegated, Delegation, Dummy, DummyWithParam}
import scala.jdk.CollectionConverters._
final class WronglyTypedContractIdIT extends LedgerTestSuite {
import CompanionImplicits._
test("WTExerciseFails", "Exercising on a wrong type fails", allocate(SingleParty))(
implicit ec => { case Participants(Participant(ledger, party)) =>
for {
dummy <- ledger.create(party, Dummy(party))
fakeDummyWithParam = dummy.asInstanceOf[Primitive.ContractId[DummyWithParam]]
dummy <- ledger.create(party, new Dummy(party))
fakeDummyWithParam = new DummyWithParam.ContractId(dummy.contractId)
exerciseFailure <- ledger
.exercise(party, fakeDummyWithParam.exerciseDummyChoice2("txt"))
.mustFail("exercising on a wrong type")
@ -35,9 +36,9 @@ final class WronglyTypedContractIdIT extends LedgerTestSuite {
test("WTFetchFails", "Fetching of the wrong type fails", allocate(SingleParty))(implicit ec => {
case Participants(Participant(ledger, party)) =>
for {
dummy <- ledger.create(party, Dummy(party))
fakeDelegated = dummy.asInstanceOf[Primitive.ContractId[Delegated]]
delegation <- ledger.create(party, Delegation(party, party))
dummy <- ledger.create(party, new Dummy(party))
fakeDelegated = new Delegated.ContractId(dummy.contractId)
delegation: Delegation.ContractId <- ledger.create(party, new Delegation(party, party))
fetchFailure <- ledger
.exercise(party, delegation.exerciseFetchDelegated(fakeDelegated))
@ -58,14 +59,16 @@ final class WronglyTypedContractIdIT extends LedgerTestSuite {
allocate(SingleParty),
)(implicit ec => { case Participants(Participant(ledger, party)) =>
for {
dummy <- ledger.create(party, Dummy(party))
fakeDummyWithParam = dummy.asInstanceOf[Primitive.ContractId[DummyWithParam]]
dummy: Dummy.ContractId <- ledger.create(party, new Dummy(party))
fakeDummyWithParam = new DummyWithParam.ContractId(dummy.contractId)
failure <- ledger
.submitAndWait(
ledger.submitAndWaitRequest(
party,
dummy.exerciseClone().command,
fakeDummyWithParam.exerciseDummyChoice2("").command,
(dummy
.exerciseClone()
.commands
.asScala ++ fakeDummyWithParam.exerciseDummyChoice2("").commands.asScala).asJava,
)
)
.mustFail("exercising on a wrong type")

View File

@ -131,46 +131,46 @@
type: jar-scala
- target: //test-common:dar-files-1.dev-lib
type: jar-scala
- target: //test-common:model-tests-1.14.scala
type: jar-scala
- target: //test-common:model-tests-1.15.scala
type: jar-scala
- target: //test-common:model-tests-1.dev.scala
type: jar-scala
- target: //test-common:package_management-tests-1.14.scala
type: jar-scala
- target: //test-common:package_management-tests-1.15.scala
type: jar-scala
- target: //test-common:package_management-tests-1.dev.scala
type: jar-scala
- target: //test-common:performance-tests-1.14.scala
type: jar-scala
- target: //test-common:performance-tests-1.15.scala
type: jar-scala
- target: //test-common:performance-tests-1.dev.scala
type: jar-scala
- target: //test-common:semantic-tests-1.14.scala
type: jar-scala
- target: //test-common:semantic-tests-1.15.scala
type: jar-scala
- target: //test-common:semantic-tests-1.dev.scala
type: jar-scala
- target: //test-common:carbonv1-tests-1.15.scala
type: jar-scala
- target: //test-common:carbonv2-tests-1.15.scala
type: jar-scala
- target: //test-common:carbonv3-tests-1.15.scala
type: jar-scala
- target: //test-common:modelext-tests-1.15.scala
type: jar-scala
- target: //test-common:carbonv1-tests-1.dev.scala
type: jar-scala
- target: //test-common:carbonv2-tests-1.dev.scala
type: jar-scala
- target: //test-common:carbonv3-tests-1.dev.scala
type: jar-scala
- target: //test-common:modelext-tests-1.dev.scala
type: jar-scala
- target: //test-common:model-tests-1.14.java-codegen
type: jar-lib
- target: //test-common:model-tests-1.15.java-codegen
type: jar-lib
- target: //test-common:model-tests-1.dev.java-codegen
type: jar-lib
- target: //test-common:package_management-tests-1.14.java-codegen
type: jar-lib
- target: //test-common:package_management-tests-1.15.java-codegen
type: jar-lib
- target: //test-common:package_management-tests-1.dev.java-codegen
type: jar-lib
- target: //test-common:performance-tests-1.14.java-codegen
type: jar-lib
- target: //test-common:performance-tests-1.15.java-codegen
type: jar-lib
- target: //test-common:performance-tests-1.dev.java-codegen
type: jar-lib
- target: //test-common:semantic-tests-1.14.java-codegen
type: jar-lib
- target: //test-common:semantic-tests-1.15.java-codegen
type: jar-lib
- target: //test-common:semantic-tests-1.dev.java-codegen
type: jar-lib
- target: //test-common:carbonv1-tests-1.15.java-codegen
type: jar-lib
- target: //test-common:carbonv2-tests-1.15.java-codegen
type: jar-lib
- target: //test-common:carbonv3-tests-1.15.java-codegen
type: jar-lib
- target: //test-common:modelext-tests-1.15.java-codegen
type: jar-lib
- target: //test-common:carbonv1-tests-1.dev.java-codegen
type: jar-lib
- target: //test-common:carbonv2-tests-1.dev.java-codegen
type: jar-lib
- target: //test-common:carbonv3-tests-1.dev.java-codegen
type: jar-lib
- target: //test-common:modelext-tests-1.dev.java-codegen
type: jar-lib
- target: //ledger-service/lf-value-json:lf-value-json
type: jar-scala
- target: //ledger-service/cli-opts:cli-opts

View File

@ -1,14 +1,14 @@
# Copyright (c) 2023 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
load(
"//bazel_tools:scala.bzl",
"da_scala_library",
)
load(
"//language-support/scala/codegen:codegen.bzl",
"dar_to_scala",
)
load(
"//language-support/java/codegen:codegen.bzl",
"dar_to_java",
)
load(
"//daml-lf/language:daml-lf.bzl",
"lf_version_configuration",
@ -107,22 +107,15 @@ da_scala_dar_resources_library(
srcjar_out = "%s-%s.scala.srcjar" % (test_name, target),
visibility = ["//visibility:public"],
),
da_scala_library(
name = "%s-tests-%s.scala" % (test_name, target),
srcs = [
":%s-tests-%s.scala-codegen" % (test_name, target),
],
scalacopts = [
"-Wconf:cat=unused-imports&site=com\\.daml\\.ledger\\.test\\.%s\\..*:s" % test_name,
],
tags = ["maven_coordinates=com.daml:test-common-%s-tests-scala-%s:__VERSION__" % (
dar_to_java(
name = "%s-tests-%s.java-codegen" % (test_name, target),
src = ":%s-tests-%s.dar" % (test_name, target),
package_prefix = "com.daml.ledger.test.java.%s" % test_name,
tags = ["maven_coordinates=com.daml:test-common-%s-tests-java-%s:__VERSION__" % (
test_name.replace("_", "-"),
target,
)],
visibility = ["//visibility:public"],
deps = [
"//language-support/scala/bindings",
],
),
]
for test_name in test_names.get(target, [])