o1-labs / o1js

TypeScript framework for zk-SNARKs and zkApps
https://docs.minaprotocol.com/en/zkapps/how-to-write-a-zkapp
Apache License 2.0
494 stars 108 forks source link

Dynamic Array Access in SnarkyJS #1062

Closed shreyas-londhe closed 4 days ago

shreyas-londhe commented 1 year ago

Hi! I was looking for a way to do array access using Field elements, but could not find any documentation for it. I would be more than happy to implement a naive quin_selector -- circom implementation for the time being, but I believe that's not a long term solution.

Any help is much appreciated!

shreyas-londhe commented 1 year ago

This is the naive implementation:

/**
 * Selects an element from an array based on an index.
 * @param arr The array to select from.
 * @param index The index of the element to select.
 * @returns The selected element.
 */
export const quinSelector = (arr: Field[], index: Field) => {
  index.lessThan(Field(arr.length)).assertTrue();

  let out = [];
  for (let i = 0; i < arr.length; i++) {
    out.push(arr[i].mul(index.equals(Field(i)).toField()));
  }

  let res = Field(0);
  for (let i = 0; i < arr.length; i++) {
    res = res.add(out[i]);
  }

  return res;
};
mitschabaude commented 1 year ago

Yep, I have used the same pattern. I don't think there's anything better without lookup based array access (which will come to snarkyjs within the next months)

Trivo25 commented 4 days ago

closing in favor of #1086