What should I do to find an existing contracts?
e.g. I have a template which create Account contract. Before creating the contract, I need to search the existing contracts to make sure the account id is not duplicated.
What should I do to find an existing contracts?
e.g. I have a template which create Account contract. Before creating the contract, I need to search the existing contracts to make sure the account id is not duplicated.
As Shayne Fletcher points out, DAML recently gained a feature called "Contract Keys" which addresses the specific issue you are trying to solve. You make use of this feature by declaring a key
on a template
together with a set of maintainers
, who ensure the uniqueness constraint in that key and validate any lookups.
template Account
with
issuer: Party
owner: Party
accountNo: Text
where
signatory issuer
observer owner
key (issuer, accountNo) : (Party, Text)
maintainer issuer
The above specifies that the tuple (issuer, accountNo)
is the "primary key" of this type of contract and that the issuer
of an account is responsible for maintaining the index for accounts issued by them.
You now have two functions at your disposal: fetchByKey
and lookupByKey
. Both take a tuple (Party, Text)
. fetchByKey
returns a tuple (ContractId Account, Account)
and aborts the transaction if the key can't be found. lookupByKey
returns an Optional (ContractId Account)
, with the additional subtlety, that the use of lookupByKey
must be authorised by the issuer
.
More generally, though, queries tend to be done off-ledger, in the integration layer of the application. If, for example, you wanted to check that a given owner
doesn't hold more than 10 account already, you would typically do that by maintaining a mirror of the active Account
templates in a queryable database of your choice and querying that before submitting your transaction.
You can have a look at this example, which maintains all active contracts in a MongoDB.