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
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
c5f7512
Add getEventsQuery definition
MartinMinkov Feb 23, 2023
c22a985
feat: Naive implementation for fetch events
MartinMinkov Feb 24, 2023
18abcac
Merge branch 'main' into feat/add-fetch-events
MartinMinkov Feb 27, 2023
898bc8e
Add functionality to remove best tip blocks
MartinMinkov Feb 27, 2023
2758ae6
Remove unused fields on fetchEvents query
MartinMinkov Feb 27, 2023
94b3fec
Add archiveGraphql Endpoint to Mina Network
MartinMinkov Mar 1, 2023
f839961
Add filter options to FetchEvents
MartinMinkov Mar 1, 2023
4279ba8
Switch to use map in Fetch.fetchEvents
MartinMinkov Mar 1, 2023
bddebc6
Add method overloading for Mina.Network
MartinMinkov Mar 2, 2023
c29f1ae
Merge branch 'main' into feat/add-fetch-events
MartinMinkov Mar 2, 2023
416e8eb
Add TODO for best tip issue
MartinMinkov Mar 2, 2023
4e15641
Changelog
MartinMinkov Mar 2, 2023
e7ce0d5
Add comments for fetchEvents
MartinMinkov Mar 2, 2023
3c82101
Remove unneeded line to method overload declaration
MartinMinkov Mar 2, 2023
2cde7f3
Reword Changelog
MartinMinkov Mar 2, 2023
07d2389
Update example using zkapp.fetchEvents
MartinMinkov Mar 2, 2023
f718457
Use real Mina Address in fetchEvents docs
MartinMinkov Mar 2, 2023
b7c41df
Feedback
MartinMinkov Mar 2, 2023
08342ec
Update comments to use unified style
MartinMinkov Mar 8, 2023
5e57898
Add better type saftey
MartinMinkov Mar 8, 2023
68eece9
Add additional block and transaction info to Fetch.fetchEvents
MartinMinkov Mar 8, 2023
dc17392
Add additional network info to zkApp.fetchEvents w/ better typing
MartinMinkov Mar 8, 2023
dc7fa1d
Match local and network versions of fetchEvents
MartinMinkov Mar 8, 2023
fc9c680
Remove toString from localblockchain events
MartinMinkov Mar 8, 2023
b81ad38
Undo previous removal of toString and call toString on network fevents
MartinMinkov Mar 8, 2023
bdcff43
Add toString() to Fetch.fetchEvents to match other APIs
MartinMinkov Mar 8, 2023
0cb36fe
minor
mitschabaude Mar 9, 2023
8aec801
Use SnarkyJS number types
MartinMinkov Mar 9, 2023
591576f
Filter out index type in Fetch.fetchEvents if only 0 is found
MartinMinkov Mar 9, 2023
dff9c56
Merge branch 'main' into feat/add-fetch-events
MartinMinkov Mar 9, 2023
fae7f57
Remove index from events
MartinMinkov Mar 10, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased](https://github.com/o1-labs/snarkyjs/compare/1abdfb70...HEAD)

### Added

- Added a new feature to the library: `fetchEvents` can now be used to fetch events for a specified zkApp from a GraphQL endpoint that implements the schema specified [here](https://github.com/o1-labs/Archive-Node-API/blob/efebc9fd3cfc028f536ae2125e0d2676e2b86cd2/src/schema.ts#L1). `Mina.Network` now accepts an additional endpoint to configure, which points to a GraphQL server running the mentioned schema. Use the `mina` property for normal usage and use `archive` to connect to the mentioned GraphQL server.

### Fixed

- Added missing export of `Mina.TransactionId` https://github.com/o1-labs/snarkyjs/pull/785
Expand Down
8 changes: 4 additions & 4 deletions src/examples/zkapps/local_events_zkapp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,14 +86,14 @@ await tx.prove();
await tx.sign([feePayerKey]).send();

console.log('---- emitted events: ----');
// fetches all events from zkapp starting slot 0
// fetches all events from zkapp starting block height 0
let events = await zkapp.fetchEvents(UInt32.from(0));
console.log(events);
console.log('---- emitted events: ----');
// fetches all events
events = await zkapp.fetchEvents();
// fetches all events from zkapp starting block height 0 and ending at block height 10
events = await zkapp.fetchEvents(UInt32.from(0), UInt64.from(10));
console.log(events);
console.log('---- emitted events: ----');
// fetches all events second time
// fetches all events
events = await zkapp.fetchEvents();
console.log(events);
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ export {
fetchAccount,
fetchLastBlock,
fetchTransactionStatus,
fetchEvents,
TransactionStatus,
addCachedAccount,
setGraphqlEndpoint,
Expand Down
152 changes: 152 additions & 0 deletions src/lib/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,24 +24,38 @@ export {
fetchMissingData,
fetchTransactionStatus,
TransactionStatus,
EventActionFilterOptions,
getCachedAccount,
getCachedNetwork,
addCachedAccount,
defaultGraphqlEndpoint,
archiveGraphqlEndpoint,
setGraphqlEndpoint,
setArchiveGraphqlEndpoint,
sendZkappQuery,
sendZkapp,
removeJsonQuotes,
fetchEvents,
};

let defaultGraphqlEndpoint = 'none';
let archiveGraphqlEndpoint = 'none';
/**
* Specifies the default GraphQL endpoint.
*/
function setGraphqlEndpoint(graphqlEndpoint: string) {
defaultGraphqlEndpoint = graphqlEndpoint;
}

/**
* Sets up a GraphQL endpoint to be used for fetching information from an Archive Node.
*
* @param A GraphQL endpoint.
*/
function setArchiveGraphqlEndpoint(graphqlEndpoint: string) {
archiveGraphqlEndpoint = graphqlEndpoint;
}

/**
* Gets account information on the specified publicKey by performing a GraphQL query
* to the specified endpoint. This will call the 'GetAccountInfo' query which fetches
Expand Down Expand Up @@ -451,6 +465,144 @@ function sendZkappQuery(json: string) {
}
`;
}
type FetchedEventActionBase = {
blockInfo: {
distanceFromMaxBlockHeight: number;
globalSlotSinceGenesis: number;
height: number;
stateHash: string;
parentHash: string;
chainStatus: string;
};
transactionInfo: {
hash: string;
memo: string;
status: string;
};
};
type FetchedEvents = {
MartinMinkov marked this conversation as resolved.
Show resolved Hide resolved
eventData: {
index: string;
data: string[];
}[];
} & FetchedEventActionBase;

type EventActionFilterOptions = {
to?: UInt32;
from?: UInt32;
};

const getEventsQuery = (
publicKey: string,
tokenId: string,
filterOptions?: EventActionFilterOptions
) => {
const { to, from } = filterOptions ?? {};
let input = `address: "${publicKey}", tokenId: "${tokenId}"`;
if (to !== undefined) {
input += `, to: ${to}`;
}
if (from !== undefined) {
input += `, from: ${from}`;
}
return `{
events(input: { ${input} }) {
blockInfo {
distanceFromMaxBlockHeight
height
globalSlotSinceGenesis
stateHash
parentHash
chainStatus
}
transactionInfo {
hash
memo
status
}
eventData {
data
}
}
}`;
};

/**
* Asynchronously fetches event data for an account from the Mina Archive Node GraphQL API.
* @async
* @param accountInfo - The account information object.
* @param accountInfo.publicKey - The account public key.
* @param [accountInfo.tokenId] - The optional token ID for the account.
* @param [graphqlEndpoint=archiveGraphqlEndpoint] - The GraphQL endpoint to query. Defaults to the Archive Node GraphQL API.
* @param [filterOptions={}] - The optional filter options object.
* @returns A promise that resolves to an array of objects containing event data, block information and transaction information for the account.
* @throws If the GraphQL request fails or the response is invalid.
* @example
* const accountInfo = { publicKey: 'B62qiwmXrWn7Cok5VhhB3KvCwyZ7NHHstFGbiU5n7m8s2RqqNW1p1wF' };
* const events = await fetchEvents(accountInfo);
* console.log(events);
*/
async function fetchEvents(
accountInfo: { publicKey: string; tokenId?: string },
graphqlEndpoint = archiveGraphqlEndpoint,
MartinMinkov marked this conversation as resolved.
Show resolved Hide resolved
filterOptions: EventActionFilterOptions = {}
) {
if (!graphqlEndpoint)
throw new Error(
'fetchEvents: Specified GraphQL endpoint is undefined. Please specify a valid endpoint.'
);
const { publicKey, tokenId } = accountInfo;
let [response, error] = await makeGraphqlRequest(
getEventsQuery(
publicKey,
tokenId ?? TokenId.toBase58(TokenId.default),
filterOptions
),
graphqlEndpoint
);
if (error) throw Error(error.statusText);
let fetchedEvents = response?.data.events as FetchedEvents[];
if (fetchedEvents === undefined) {
throw Error(
`Failed to fetch events data. Account: ${publicKey} Token: ${tokenId}`
);
}

// TODO: This is a temporary fix. We should be able to fetch the event/action data from any block at the best tip.
// Once https://github.com/o1-labs/Archive-Node-API/issues/7 is resolved, we can remove this.
// If we have multiple blocks returned at the best tip (e.g. distanceFromMaxBlockHeight === 0),
// then filter out the blocks at the best tip. This is because we cannot guarantee that every block
// at the best tip will have the correct event data or guarantee that the specific block data will not
// fork in anyway. If this happens, we delay fetching event data until another block has been added to the network.
let numberOfBestTipBlocks = 0;
for (let i = 0; i < fetchedEvents.length; i++) {
if (fetchedEvents[i].blockInfo.distanceFromMaxBlockHeight === 0) {
numberOfBestTipBlocks++;
}
if (numberOfBestTipBlocks > 1) {
fetchedEvents = fetchedEvents.filter((event) => {
return event.blockInfo.distanceFromMaxBlockHeight !== 0;
});
break;
}
}

return fetchedEvents.map((event) => {
let events = event.eventData.map((eventData) => eventData.data);

return {
events,
blockHeight: UInt32.from(event.blockInfo.height),
blockHash: event.blockInfo.stateHash,
parentBlockHash: event.blockInfo.parentHash,
globalSlot: UInt32.from(event.blockInfo.globalSlotSinceGenesis),
chainStatus: event.blockInfo.chainStatus,
transactionHash: event.transactionInfo.hash,
transactionStatus: event.transactionInfo.status,
transactionMemo: event.transactionInfo.memo,
};
});
}

// removes the quotes on JSON keys
function removeJsonQuotes(json: string) {
Expand Down
68 changes: 54 additions & 14 deletions src/lib/mina.ts
Original file line number Diff line number Diff line change
Expand Up @@ -321,7 +321,11 @@ interface Mina {
};
accountCreationFee(): UInt64;
sendTransaction(transaction: Transaction): Promise<TransactionId>;
fetchEvents: (publicKey: PublicKey, tokenId?: Field) => any;
fetchEvents: (
publicKey: PublicKey,
tokenId?: Field,
filterOptions?: Fetch.EventActionFilterOptions
) => ReturnType<typeof Fetch.fetchEvents>;
getActions: (
publicKey: PublicKey,
tokenId?: Field
Expand Down Expand Up @@ -461,7 +465,16 @@ function LocalBlockchain({
}
events[addr][tokenId].push({
events: p.body.events,
slot: networkState.globalSlotSinceGenesis.toString(),
blockHeight: networkState.blockchainLength,
globalSlot: networkState.globalSlotSinceGenesis,
// The following fields are fetched from the Mina network. For now, we mock these values out
// since networkState does not contain these fields.
blockHash: '',
parentBlockHash: '',
chainStatus: '',
transactionHash: '',
transactionStatus: '',
transactionMemo: '',
});
}

Expand Down Expand Up @@ -543,10 +556,7 @@ function LocalBlockchain({
JSON.stringify(networkState)
);
},
async fetchEvents(
publicKey: PublicKey,
tokenId: Field = TokenId.default
): Promise<any[]> {
async fetchEvents(publicKey: PublicKey, tokenId: Field = TokenId.default) {
return events?.[publicKey.toBase58()]?.[TokenId.toBase58(tokenId)] ?? [];
},
getActions(
Expand Down Expand Up @@ -588,9 +598,26 @@ LocalBlockchain satisfies (...args: any) => Mina;
/**
* Represents the Mina blockchain running on a real network
*/
function Network(graphqlEndpoint: string): Mina {
function Network(graphqlEndpoint: string): Mina;
function Network(graphqlEndpoints: { mina: string; archive: string }): Mina;
function Network(input: { mina: string; archive: string } | string): Mina {
let accountCreationFee = UInt64.from(defaultAccountCreationFee);
Fetch.setGraphqlEndpoint(graphqlEndpoint);
let graphqlEndpoint: string;
let archiveEndpoint: string;

if (input && typeof input === 'string') {
graphqlEndpoint = input;
Fetch.setGraphqlEndpoint(graphqlEndpoint);
} else if (input && typeof input === 'object') {
graphqlEndpoint = input.mina;
archiveEndpoint = input.archive;
Fetch.setGraphqlEndpoint(graphqlEndpoint);
Fetch.setArchiveGraphqlEndpoint(archiveEndpoint);
} else {
throw new Error(
"Network: malformed input. Please provide a string or an object with 'mina' and 'archive' endpoints."
);
}

// copied from mina/genesis_ledgers/berkeley.json
// TODO fetch from graphql instead of hardcoding
Expand Down Expand Up @@ -756,9 +783,18 @@ function Network(graphqlEndpoint: string): Mina {
isFinalRunOutsideCircuit: !hasProofs,
});
},
async fetchEvents() {
throw Error(
'fetchEvents() is not implemented yet for remote blockchains.'
async fetchEvents(
publicKey: PublicKey,
tokenId: Field = TokenId.default,
filterOptions: Fetch.EventActionFilterOptions = {}
) {
let pubKey = publicKey.toBase58();
let token = TokenId.toBase58(tokenId);

return Fetch.fetchEvents(
{ publicKey: pubKey, tokenId: token },
archiveEndpoint,
filterOptions
);
},
getActions() {
Expand Down Expand Up @@ -838,7 +874,7 @@ let activeInstance: Mina = {
async transaction(sender: DeprecatedFeePayerSpec, f: () => void) {
return createTransaction(sender, f, 0);
},
fetchEvents() {
fetchEvents(publicKey: PublicKey, tokenId: Field = TokenId.default) {
throw Error('must call Mina.setActiveInstance first');
},
getActions() {
Expand Down Expand Up @@ -976,8 +1012,12 @@ async function sendTransaction(txn: Transaction) {
/**
* @return A list of emitted events associated to the given public key.
*/
async function fetchEvents(publicKey: PublicKey, tokenId: Field) {
return await activeInstance.fetchEvents(publicKey, tokenId);
async function fetchEvents(
publicKey: PublicKey,
tokenId: Field,
filterOptions: Fetch.EventActionFilterOptions = {}
) {
return await activeInstance.fetchEvents(publicKey, tokenId, filterOptions);
}

/**
Expand Down
Loading