Joel
Joel

Reputation: 23140

In Corda transaction, getting command associated with specific state

I have a Corda transaction with multiple states and multiple commands. How can I associate each state to its corresponding command?

Upvotes: 0

Views: 178

Answers (2)

Adrian
Adrian

Reputation: 444

This is what I do for my use-case.

class Reject(val linearIds: List<UniqueIdentifier>) : TypeOnlyCommandData(), Commands


val correspondingStatesToEnforce = tx.inputsOfType<Obligation>()
.filter { it.linearId in command.linearIds }

require(...)

Upvotes: 0

Joel
Joel

Reputation: 23140

There is no mapping of states to commands in a transaction. Each transaction has one or more commands and one or more states, but they are not required to be related in any way.

However, the pattern you will generally see is:

  • A state's contract checks for a specific command type
  • Based on the command's type, the contract checks constraints about the states

For example:

class MyContract : Contract {
    override fun verify(tx: LedgerTransaction) {
        val command = tx.commands.requireSingleCommand<Commands>()

        when (command.value) {
            is Commands.MyCommand1 -> {
                if (tx.inputStates.size != 1) 
                    throw IllegalArgumentException("When its a MyCommand1 transaction, there must be one input.")
                TODO("More checking.")
            }

            is Commands.MyCommand2 -> {
                if (tx.inputStates.size != 2)
                    throw IllegalArgumentException("When its a MyCommand1 transaction, there must be two inputs.")
                TODO("More checking.")
            }
        }

    }

    interface Commands : CommandData {
        class MyCommand1 : Commands
        class MyCommand2 : Commands
    }
}

Upvotes: 0

Related Questions