'Are there ways to perform membership tests in pact? (performing membership test for pact tables)

Hello to the kadena pact developer community

I was looking at some basic code examples and as I wanted to play around with the functionality to develop a better grasp for it, I got curios about the following:

We see that some capabilities as defined in example code test for values within a row inside a table. Is there a way one could simply test for a key and fail the predicate if the key is not present in the table?

Thank you for your insight.



Solution 1:[1]

While this may not be the most efficient way, I have found a solution to the question.

The pact syntax for testing membership is with the function call to 'contains' enter image description here

Now we want to know whether a key exists within our table. In order to do this we can use the built-in function 'keys' enter image description here

This will return a list of strings (i.e. our keys) and will let us query via the use of 'contains' whether the key in question exists as a key in our table, or: is X a member in our table.

Since this requires us to get a complete list of keys just to see whether the particular key is within our table, this is where my concern regarding performance comes in. I wanted to share this with everyone, regardless, but in certain circumstances it may be better to just let the transaction fail instead of enforcing membership explicitly like this.

Edit: I used some code previously to show how to achieve this, but it was faulty code. If you need a membership test, you can do it within the context of an if statement, but not with (enforce ) as enforce will only allow "pure" expressions (i.e. expressions that can be evaluated on the spot and do not involve database lookups like the 'keys' function).

Enforcing a test outcome that requires database transaction will return an error like

Error from (api.testnet.chainweb.com): : Failure: Database exception: : Failure: Illegal database access attempt (keys)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1