-
Notifications
You must be signed in to change notification settings - Fork 142
/
Copy pathfetch.ts
671 lines (637 loc) · 18 KB
/
fetch.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
import 'isomorphic-fetch';
import { Bool, Field, Ledger } from '../snarky.js';
import { UInt32, UInt64 } from './int.js';
import { TokenId, Permissions, ZkappStateLength } from './account_update.js';
import { PublicKey } from './signature.js';
import { NetworkValue } from './precondition.js';
import { Types } from '../provable/types.js';
import * as Encoding from './encoding.js';
export {
fetchAccount,
fetchLastBlock,
parseFetchedAccount,
markAccountToBeFetched,
markNetworkToBeFetched,
fetchMissingData,
fetchTransactionStatus,
TransactionStatus,
getCachedAccount,
getCachedNetwork,
addCachedAccount,
defaultGraphqlEndpoint,
setGraphqlEndpoint,
sendZkappQuery,
sendZkapp,
removeJsonQuotes,
};
export { Account };
let defaultGraphqlEndpoint = 'none';
/**
* Specifies the default GraphQL endpoint.
*/
function setGraphqlEndpoint(graphqlEndpoint: string) {
defaultGraphqlEndpoint = 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
* zkapp related account information.
*
* If an error is returned by the specified endpoint, an error is thrown. Otherwise,
* the data is returned.
*
* @param publicKey The specified account to get account information on
* @param graphqlEndpoint The graphql endpoint to fetch from
* @param config An object that exposes an additional timeout option
* @returns zkapp information on the specified account or an error is thrown
*/
async function fetchAccount(
accountInfo: { publicKey: string | PublicKey; tokenId?: string },
graphqlEndpoint = defaultGraphqlEndpoint,
{ timeout = defaultTimeout } = {}
): Promise<
| { account: Account; error: undefined }
| { account: undefined; error: FetchError }
> {
let publicKeyBase58 =
accountInfo.publicKey instanceof PublicKey
? accountInfo.publicKey.toBase58()
: accountInfo.publicKey;
let response = await fetchAccountInternal(
{ publicKey: publicKeyBase58, tokenId: accountInfo.tokenId },
graphqlEndpoint,
{
timeout,
}
);
return response.error === undefined
? {
account: parseFetchedAccount(response.account),
error: undefined,
}
: { account: undefined, error: response.error };
}
// internal version of fetchAccount which does the same, but returns the original JSON version
// of the account, to save some back-and-forth conversions when caching accounts
async function fetchAccountInternal(
accountInfo: { publicKey: string; tokenId?: string },
graphqlEndpoint = defaultGraphqlEndpoint,
config?: FetchConfig
) {
const { publicKey, tokenId } = accountInfo;
let [response, error] = await makeGraphqlRequest(
accountQuery(publicKey, tokenId ?? TokenId.toBase58(TokenId.default)),
graphqlEndpoint,
config
);
if (error !== undefined) return { account: undefined, error };
let account = (response as FetchResponse).data
.account as FetchedAccount | null;
if (account === null) {
return {
account: undefined,
error: {
statusCode: 404,
statusText: `fetchAccount: Account with public key ${publicKey} does not exist.`,
},
};
}
// account successfully fetched - add to cache before returning
addCachedAccountInternal(account, graphqlEndpoint);
return {
account,
error: undefined,
};
}
type FetchConfig = { timeout?: number };
type FetchResponse = { data: any };
type FetchError = {
statusCode: number;
statusText: string;
};
// Specify 30s as the default timeout
const defaultTimeout = 30000;
type AuthRequired = Types.Json.AuthRequired;
type FetchedAccount = {
publicKey: string;
nonce: string;
token: string;
tokenSymbol: string;
zkappUri?: string;
zkappState: string[] | null;
receiptChainHash?: string;
balance: { total: string };
permissions?: NonNullable<
Types.Json.AccountUpdate['body']['update']['permissions']
>;
delegateAccount?: { publicKey: string };
sequenceEvents?: string[] | null;
verificationKey?: { verificationKey: string; hash: string };
// TODO: how to query provedState?
};
type Account = {
publicKey: PublicKey;
nonce: UInt32;
balance: UInt64;
tokenId: Field;
tokenSymbol: string;
appState?: Field[];
permissions?: Permissions;
receiptChainHash: Field;
delegate?: PublicKey;
sequenceState?: Field;
provedState: Bool;
verificationKey?: { data: string; hash: Field };
timing?: NonNullable<
Types.AccountUpdate['body']['update']['timing']['value']
> & {
isTimed: Bool;
};
};
type FlexibleAccount = {
publicKey: PublicKey | string;
nonce: UInt32 | string | number;
tokenId?: string;
tokenSymbol?: string;
balance?: UInt64 | string | number;
zkapp?: {
appState: (Field | string | number)[];
verificationKey?: { data: string; hash: string };
};
};
// TODO provedState
const accountQuery = (publicKey: string, tokenId: string) => `{
account(publicKey: "${publicKey}", token: "${tokenId}") {
publicKey
nonce
zkappUri
zkappState
permissions {
editState
send
receive
setDelegate
setPermissions
setVerificationKey
setZkappUri
editSequenceState
setTokenSymbol
incrementNonce
setVotingFor
setTiming
}
receiptChainHash
balance { total }
delegateAccount { publicKey }
sequenceEvents
token
tokenSymbol
verificationKey {
verificationKey
}
}
}
`;
// TODO automate these conversions (?)
function parseFetchedAccount(account: FetchedAccount): Account;
function parseFetchedAccount(
account: Partial<FetchedAccount>
): Partial<Account>;
function parseFetchedAccount({
publicKey,
nonce,
zkappState,
balance,
permissions,
delegateAccount,
receiptChainHash,
sequenceEvents,
token,
tokenSymbol,
verificationKey,
}: Partial<FetchedAccount>): Partial<Account> {
return {
publicKey:
publicKey !== undefined ? PublicKey.fromBase58(publicKey) : undefined,
nonce: nonce !== undefined ? UInt32.from(nonce) : undefined,
balance: balance && UInt64.from(balance.total),
appState: (zkappState && zkappState.map(Field)) ?? undefined,
permissions:
permissions &&
(Object.fromEntries(
Object.entries(permissions).map(([k, v]) => [
k,
Permissions.fromString(v),
])
) as unknown as Permissions),
sequenceState:
sequenceEvents != undefined ? Field(sequenceEvents[0]) : undefined,
receiptChainHash:
receiptChainHash !== undefined
? Encoding.ReceiptChainHash.fromBase58(receiptChainHash)
: undefined,
delegate:
delegateAccount && PublicKey.fromBase58(delegateAccount.publicKey),
tokenId: token !== undefined ? Ledger.fieldOfBase58(token) : undefined,
tokenSymbol: tokenSymbol !== undefined ? tokenSymbol : undefined,
verificationKey: verificationKey && {
data: verificationKey.verificationKey,
hash: Field(verificationKey.hash),
},
};
}
function stringifyAccount(account: FlexibleAccount): FetchedAccount {
let { publicKey, nonce, balance, zkapp, tokenId, tokenSymbol } = account;
return {
publicKey:
publicKey instanceof PublicKey ? publicKey.toBase58() : publicKey,
nonce: nonce?.toString(),
zkappState:
zkapp?.appState.map((s) => s.toString()) ??
Array(ZkappStateLength).fill('0'),
balance: { total: balance?.toString() ?? '0' },
token: tokenId ?? TokenId.toBase58(TokenId.default),
tokenSymbol: tokenSymbol ?? '',
verificationKey: zkapp?.verificationKey && {
verificationKey: zkapp?.verificationKey.data,
hash: zkapp?.verificationKey.hash,
},
};
}
let accountCache = {} as Record<
string,
{
account: FetchedAccount;
graphqlEndpoint: string;
timestamp: number;
}
>;
let networkCache = {} as Record<
string,
{
network: NetworkValue;
graphqlEndpoint: string;
timestamp: number;
}
>;
let accountsToFetch = {} as Record<
string,
{ publicKey: string; tokenId: string; graphqlEndpoint: string }
>;
let networksToFetch = {} as Record<string, { graphqlEndpoint: string }>;
function markAccountToBeFetched(
publicKey: PublicKey,
tokenId: Field,
graphqlEndpoint: string
) {
let publicKeyBase58 = publicKey.toBase58();
let tokenBase58 = TokenId.toBase58(tokenId);
accountsToFetch[`${publicKeyBase58};${tokenBase58};${graphqlEndpoint}`] = {
publicKey: publicKeyBase58,
tokenId: tokenBase58,
graphqlEndpoint,
};
}
function markNetworkToBeFetched(graphqlEndpoint: string) {
networksToFetch[graphqlEndpoint] = { graphqlEndpoint };
}
async function fetchMissingData(graphqlEndpoint: string) {
let promises = Object.entries(accountsToFetch).map(
async ([key, { publicKey, tokenId }]) => {
let response = await fetchAccountInternal(
{ publicKey, tokenId },
graphqlEndpoint
);
if (response.error === undefined) delete accountsToFetch[key];
}
);
let network = Object.entries(networksToFetch).find(([, network]) => {
return network.graphqlEndpoint === graphqlEndpoint;
});
if (network !== undefined) {
promises.push(
(async () => {
try {
await fetchLastBlock(graphqlEndpoint);
delete networksToFetch[network[0]];
} catch {}
})()
);
}
await Promise.all(promises);
}
function getCachedAccount(
publicKey: PublicKey,
tokenId: Field,
graphqlEndpoint = defaultGraphqlEndpoint
) {
let account =
accountCache[
`${publicKey.toBase58()};${TokenId.toBase58(tokenId)};${graphqlEndpoint}`
]?.account;
if (account !== undefined) return parseFetchedAccount(account);
}
function getCachedNetwork(graphqlEndpoint = defaultGraphqlEndpoint) {
return networkCache[graphqlEndpoint]?.network;
}
/**
* Adds an account to the local cache, indexed by a GraphQL endpoint.
*/
function addCachedAccount(
account: {
publicKey: string | PublicKey;
nonce: string | number | UInt32;
balance?: string | number | UInt64;
zkapp?: {
appState: (string | number | Field)[];
verificationKey?: { data: string; hash: string };
};
tokenId: string;
},
graphqlEndpoint = defaultGraphqlEndpoint
) {
addCachedAccountInternal(stringifyAccount(account), graphqlEndpoint);
}
function addCachedAccountInternal(
account: FetchedAccount,
graphqlEndpoint: string
) {
accountCache[`${account.publicKey};${account.token};${graphqlEndpoint}`] = {
account,
graphqlEndpoint,
timestamp: Date.now(),
};
}
/**
* Fetches the last block on the Mina network.
*/
async function fetchLastBlock(graphqlEndpoint = defaultGraphqlEndpoint) {
let [resp, error] = await makeGraphqlRequest(lastBlockQuery, graphqlEndpoint);
if (error) throw Error(error.statusText);
let lastBlock = resp?.data?.bestChain?.[0];
if (lastBlock === undefined) {
throw Error('Failed to fetch latest network state.');
}
let network = parseFetchedBlock(lastBlock);
networkCache[graphqlEndpoint] = {
network,
graphqlEndpoint,
timestamp: Date.now(),
};
return network;
}
const lastBlockQuery = `{
bestChain(maxLength: 1) {
protocolState {
blockchainState {
snarkedLedgerHash
stagedLedgerHash
date
utcDate
stagedLedgerProofEmitted
}
previousStateHash
consensusState {
blockHeight
slotSinceGenesis
slot
nextEpochData {
ledger {hash totalCurrency}
seed
startCheckpoint
lockCheckpoint
epochLength
}
stakingEpochData {
ledger {hash totalCurrency}
seed
startCheckpoint
lockCheckpoint
epochLength
}
epochCount
minWindowDensity
totalCurrency
epoch
}
}
}
}`;
type FetchedBlock = {
protocolState: {
blockchainState: {
snarkedLedgerHash: string; // hash-like encoding
stagedLedgerHash: string; // hash-like encoding
date: string; // String(Date.now())
utcDate: string; // String(Date.now())
stagedLedgerProofEmitted: boolean; // bool
};
previousStateHash: string; // hash-like encoding
consensusState: {
blockHeight: string; // String(number)
slotSinceGenesis: string; // String(number)
slot: string; // String(number)
nextEpochData: {
ledger: {
hash: string; // hash-like encoding
totalCurrency: string; // String(number)
};
seed: string; // hash-like encoding
startCheckpoint: string; // hash-like encoding
lockCheckpoint: string; // hash-like encoding
epochLength: string; // String(number)
};
stakingEpochData: {
ledger: {
hash: string; // hash-like encoding
totalCurrency: string; // String(number)
};
seed: string; // hash-like encoding
startCheckpoint: string; // hash-like encoding
lockCheckpoint: string; // hash-like encoding
epochLength: string; // String(number)
};
epochCount: string; // String(number)
minWindowDensity: string; // String(number)
totalCurrency: string; // String(number)
epoch: string; // String(number)
};
};
};
function parseFetchedBlock({
protocolState: {
blockchainState: { snarkedLedgerHash, utcDate },
consensusState: {
blockHeight,
minWindowDensity,
totalCurrency,
slot,
slotSinceGenesis,
nextEpochData,
stakingEpochData,
},
},
}: FetchedBlock): NetworkValue {
return {
snarkedLedgerHash: Encoding.LedgerHash.fromBase58(snarkedLedgerHash),
// TODO: use date or utcDate?
blockchainLength: UInt32.from(blockHeight),
minWindowDensity: UInt32.from(minWindowDensity),
totalCurrency: UInt64.from(totalCurrency),
globalSlotSinceGenesis: UInt32.from(slotSinceGenesis),
nextEpochData: parseEpochData(nextEpochData),
stakingEpochData: parseEpochData(stakingEpochData),
};
}
function parseEpochData({
ledger: { hash, totalCurrency },
seed,
startCheckpoint,
lockCheckpoint,
epochLength,
}: FetchedBlock['protocolState']['consensusState']['nextEpochData']): NetworkValue['nextEpochData'] {
return {
ledger: {
hash: Encoding.LedgerHash.fromBase58(hash),
totalCurrency: UInt64.from(totalCurrency),
},
seed: Encoding.EpochSeed.fromBase58(seed),
startCheckpoint: Encoding.StateHash.fromBase58(startCheckpoint),
lockCheckpoint: Encoding.StateHash.fromBase58(lockCheckpoint),
epochLength: UInt32.from(epochLength),
};
}
const transactionStatusQuery = (txId: string) => `query {
transactionStatus(zkappTransaction:"${txId}")
}`;
/**
* Fetches the status of a transaction.
*/
async function fetchTransactionStatus(
txId: string,
graphqlEndpoint = defaultGraphqlEndpoint
): Promise<TransactionStatus> {
let [resp, error] = await makeGraphqlRequest(
transactionStatusQuery(txId),
graphqlEndpoint
);
if (error) throw Error(error.statusText);
let txStatus = resp?.data?.transactionStatus;
if (txStatus === undefined || txStatus === null) {
throw Error(`Failed to fetch transaction status. TransactionId: ${txId}`);
}
return txStatus as TransactionStatus;
}
/**
* INCLUDES: A transaction that is on the longest chain
*
* PENDING: A transaction either in the transition frontier or in transaction pool but is not on the longest chain
*
* UNKNOWN: The transaction has either been snarked, reached finality through consensus or has been dropped
*
*/
type TransactionStatus = 'INCLUDED' | 'PENDING' | 'UNKNOWN';
/**
* Sends a zkApp command (transaction) to the specified GraphQL endpoint.
*/
function sendZkapp(
json: string,
graphqlEndpoint = defaultGraphqlEndpoint,
{ timeout = defaultTimeout } = {}
) {
return makeGraphqlRequest(sendZkappQuery(json), graphqlEndpoint, {
timeout,
});
}
// TODO: Decide an appropriate response structure.
function sendZkappQuery(json: string) {
return `mutation {
sendZkapp(input: {
zkappCommand: ${removeJsonQuotes(json)}
}) {
zkapp {
hash
id
failureReason {
failures
index
}
zkappCommand {
memo
feePayer {
body {
publicKey
}
}
accountUpdates {
body {
publicKey
useFullCommitment
incrementNonce
}
}
}
}
}
}
`;
}
// removes the quotes on JSON keys
function removeJsonQuotes(json: string) {
let cleaned = JSON.stringify(JSON.parse(json), null, 2);
return cleaned.replace(/\"(\S+)\"\s*:/gm, '$1:');
}
// TODO it seems we're not actually catching most errors here
async function makeGraphqlRequest(
query: string,
graphqlEndpoint = defaultGraphqlEndpoint,
{ timeout = defaultTimeout } = {} as FetchConfig
) {
if (graphqlEndpoint === 'none')
throw Error(
"Should have made a graphql request, but don't know to which endpoint. Try calling `setGraphqlEndpoint` first."
);
const controller = new AbortController();
const timer = setTimeout(() => {
controller.abort();
}, timeout);
try {
let body = JSON.stringify({ operationName: null, query, variables: {} });
let response = await fetch(graphqlEndpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body,
signal: controller.signal,
});
return await checkResponseStatus(response);
} catch (error) {
clearTimeout(timer);
return [undefined, inferError(error)] as [undefined, FetchError];
}
}
async function checkResponseStatus(
response: Response
): Promise<[FetchResponse, undefined] | [undefined, FetchError]> {
if (response.ok) {
return [(await response.json()) as FetchResponse, undefined];
} else {
return [
undefined,
{
statusCode: response.status,
statusText: response.statusText,
} as FetchError,
];
}
}
function inferError(error: unknown): FetchError {
let errorMessage = JSON.stringify(error);
if (error instanceof AbortSignal) {
return { statusCode: 408, statusText: `Request Timeout: ${errorMessage}` };
} else {
return {
statusCode: 500,
statusText: `Unknown Error: ${errorMessage}`,
};
}
}