0

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.

Frankie
  • 113
  • 5
  • It sounds likely that a soon to be released feature called "contract keys" might be brought to bear on this problem. With this you'll be able to efficiently determine if there is an existing contract associated with a candidate account ID. Please keep an eye out on our blogs in the coming week for more information about that. In the meantime, I hope/expect that others will jump in your question and offer shorter term solutions! – Shayne Fletcher May 07 '19 at 23:41
  • It seems that the latest DAML allows you to create template with keys. And those keys can be used in the functions such as fetch or lookup. I will try it. – Frankie May 09 '19 at 07:18

1 Answers1

0

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.

bame
  • 960
  • 5
  • 7
  • I wanted to maintains all the active contracts in a DB as well. Would you mind sharing your code. I am not able to make it work. I implemented a BOT. – dagra Nov 11 '19 at 04:21