Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add fetch events to network API #749

Merged
merged 31 commits into from
Mar 13, 2023
Merged

Add fetch events to network API #749

merged 31 commits into from
Mar 13, 2023

Conversation

MartinMinkov
Copy link
Contributor

@MartinMinkov MartinMinkov commented Feb 24, 2023

Description

This PR supports fetching events from a GraphQL API that implements the following schema. It aims to keep the API functionality as the existing fetch events API.

The following changes have been made:

  1. Add method overloading to the Mina.Network function to take in an object that can specify an endpoint to be used for the archive API.
  2. Add support to fetch events from the archive API in the Fetch module. Fetching events is done by the newly added fetchEvents function that is exposed.
  3. Refactor the existing fetchEvents function inside zkapp.ts to filter by block heights instead of slots.

Impact

By adding a way to fetch events for SnarkyJS, zkApps can now reliably fetch its event data from a datastore (like the Archive Node). This unlocks many use cases as Events can notify that the state has changed or even as a basic solution to off-chain storage.

Tested

Manual testing uses an internally deployed archive API and matching deployed zkApp to fetch events.

If you wish to test the newly added functionality, run this build and use this script:

import {
  Field,
  state,
  State,
  UInt32,
  fetchEvents,
  method,
  PrivateKey,
  SmartContract,
  Mina,
  isReady,
  shutdown,
  PublicKey,
  Reducer,
  Permissions,
} from 'snarkyjs';

await isReady;

const INCREMENT = Field(1);

export class SimpleZkapp extends SmartContract {
  @state(Field) x = State<Field>();
  @state(Field) y = State<Field>();

  @state(Field) counter = State<Field>();
  @state(Field) actionsHash = State<Field>();

  events = {
    updateValue: Field,
    newState: Field,
    address: PublicKey,
  };

  reducer = Reducer({ actionType: Field });

  init(zkappKey: PrivateKey) {
    super.init(zkappKey);
    this.x.set(initialState);
    this.y.set(Field(0));
    this.counter.set(Field(0));
    this.actionsHash.set(Reducer.initialActionsHash);
    this.account.permissions.set({
      ...Permissions.default(),
      send: Permissions.proofOrSignature(),
      receive: Permissions.proofOrSignature(),
    });
  }

  @method rollupIncrements() {
    // get previous counter & actions hash, assert that they're the same as on-chain values
    let counter = this.counter.get();
    this.counter.assertEquals(counter);
    let actionsHash = this.actionsHash.get();
    this.actionsHash.assertEquals(actionsHash);

    // compute the new counter and hash from pending actions
    let pendingActions = this.reducer.getActions({
      fromActionHash: actionsHash,
    });

    let { state: newCounter, actionsHash: newActionsHash } =
      this.reducer.reduce(
        pendingActions,
        // state type
        Field,
        // function that says how to apply an action
        (state: Field, _action: Field) => {
          return state.add(1);
        },
        { state: counter, actionsHash }
      );

    // update on-chain state
    this.counter.set(newCounter);
    this.actionsHash.set(newActionsHash);
  }

  @method update(z: Field): Field {
    this.emitEvent('updateValue', z);
    let x = this.x.get();
    this.x.assertEquals(x);
    let newX = x.add(z);
    this.x.set(newX);
    this.y.set(z);
    this.emitEvent('newState', newX);
    this.emitEvent('address', this.address);

    this.reducer.dispatch(INCREMENT);

    return newX;
  }
}

let Berkeley = Mina.Network({
  mina: 'https://proxy.berkeley.minaexplorer.com/graphql',
  archive: 'https://archive.berkeley.minaexplorer.com/',
});
Mina.setActiveInstance(Berkeley);

// the zkapp account
const address = PublicKey.fromBase58(
  'B62qrfn5xxChtPGJne9HuDJZ4ziWVgWxeL3hntGBqMmf45p4hudo3tw'
);
let initialState = Field(1);
let zkapp = new SimpleZkapp(address);

console.log('---- emitted events: ----');
// fetches all events from zkapp starting block 0
let events = await zkapp.fetchEvents(UInt32.from(0));
console.log(events);
console.log('---- emitted events: ----');
// fetches all events starting at block 560 and ending at block 600
events = await zkapp.fetchEvents(UInt32.from(560), UInt32.from(600));
console.log(events);
console.log('---- emitted events: ----');
// fetches all events
events = await zkapp.fetchEvents();
console.log(events);
console.log('---- emitted events: ----');
events = await fetchEvents({
  publicKey: 'B62qrfn5xxChtPGJne9HuDJZ4ziWVgWxeL3hntGBqMmf45p4hudo3tw',
});
console.log(events);
await shutdown();

Example Output

When fetching events locally, events will look like:

let events = await zkapp.fetchEvents();
// Returned
[
  {
    type: 'simpleEvent',
    event: { value: [Array] },
    blockHeight: '0',
    blockHash: '',
    parentBlockHash: '',
    globalSlot: '0',
    chainStatus: '',
    transactionHash: '',
    transactionStatus: '',
    transactionMemo: ''
  },
  {
    type: 'complexEvent',
    event: Event { pub: [PublicKey], value: [Object] },
    blockHeight: '0',
    blockHash: '',
    parentBlockHash: '',
    globalSlot: '0',
    chainStatus: '',
    transactionHash: '',
    transactionStatus: '',
    transactionMemo: ''
  },
...
]

Fetching using the network API, with the script above looks like:

let events = await zkapp.fetchEvents();
// Returned
[
  {
    type: 'address',
    event: PublicKey { x: [Object], isOdd: [Object] },
    blockHeight: 600,
    blockHash: '3NKhg5GcmczaffFMRienet3doYuyzZ1Pe6CLpmioqTFWenaEhVBE',
    parentBlockHash: '3NLxzAPngJYcAPVHXsxyEnsbn2AeDPNP6MRKUg1iaEKRzBVzaMaw',
    globalSlot: 1519,
    chainStatus: 'canonical',
    transactionHash: '5JubYLuiRuBYn4JcHFBBnKC2HoLd9YDMRKKfmK15rsH1mt7MLhud',
    transactionStatus: 'applied',
    transactionMemo: 'E4YM2vTHhWEg66xpj52JErHUBU4pZ1yageL4TVDDpTTSsv8mK6YaH'
  },
  {
    type: 'newState',
    event: { value: [Array] },
    blockHeight: 600,
    blockHash: '3NKhg5GcmczaffFMRienet3doYuyzZ1Pe6CLpmioqTFWenaEhVBE',
    parentBlockHash: '3NLxzAPngJYcAPVHXsxyEnsbn2AeDPNP6MRKUg1iaEKRzBVzaMaw',
    globalSlot: 1519,
    chainStatus: 'canonical',
    transactionHash: '5JubYLuiRuBYn4JcHFBBnKC2HoLd9YDMRKKfmK15rsH1mt7MLhud',
    transactionStatus: 'applied',
    transactionMemo: 'E4YM2vTHhWEg66xpj52JErHUBU4pZ1yageL4TVDDpTTSsv8mK6YaH'
  },
  {
    type: 'updateValue',
    event: { value: [Array] },
    blockHeight: 600,
    blockHash: '3NKhg5GcmczaffFMRienet3doYuyzZ1Pe6CLpmioqTFWenaEhVBE',
    parentBlockHash: '3NLxzAPngJYcAPVHXsxyEnsbn2AeDPNP6MRKUg1iaEKRzBVzaMaw',
    globalSlot: 1519,
    chainStatus: 'canonical',
    transactionHash: '5JubYLuiRuBYn4JcHFBBnKC2HoLd9YDMRKKfmK15rsH1mt7MLhud',
    transactionStatus: 'applied',
    transactionMemo: 'E4YM2vTHhWEg66xpj52JErHUBU4pZ1yageL4TVDDpTTSsv8mK6YaH'
  }
  ...
]

@MartinMinkov MartinMinkov marked this pull request as ready for review March 2, 2023 18:53
Copy link
Member

@Trivo25 Trivo25 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

awesome! Just left a few comments :)

CHANGELOG.md Outdated Show resolved Hide resolved
src/lib/fetch.ts Show resolved Hide resolved
src/lib/fetch.ts Outdated Show resolved Hide resolved
Copy link
Collaborator

@mitschabaude mitschabaude left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very nice! I have a few comments mostly about type safety

src/lib/mina.ts Outdated Show resolved Hide resolved
src/lib/fetch.ts Outdated Show resolved Hide resolved
src/lib/fetch.ts Outdated Show resolved Hide resolved
src/lib/fetch.ts Outdated Show resolved Hide resolved
src/lib/zkapp.ts Outdated Show resolved Hide resolved
src/lib/zkapp.ts Outdated Show resolved Hide resolved
src/lib/zkapp.ts Outdated Show resolved Hide resolved
Copy link
Collaborator

@mitschabaude mitschabaude left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks great to me! I have some feedback regarding the event types we expose, but that could be addressed elsewhere if we want to get this out quickly

src/lib/fetch.ts Show resolved Hide resolved
src/lib/zkapp.ts Outdated Show resolved Hide resolved
src/lib/zkapp.ts Outdated Show resolved Hide resolved
src/lib/zkapp.ts Outdated Show resolved Hide resolved
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants