-
Notifications
You must be signed in to change notification settings - Fork 241
/
anchor.tsx
42 lines (38 loc) · 1.34 KB
/
anchor.tsx
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
import { NodeWallet } from '@metaplex/js';
import { Idl, Program, Provider } from '@project-serum/anchor';
import { Connection, Keypair } from '@solana/web3.js';
const cachedAnchorProgramPromises: Record<
string,
void | { __type: 'promise'; promise: Promise<void> } | { __type: 'result'; result: Program<Idl> | null }
> = {};
export function useAnchorProgram(programAddress: string, url: string): Program | null {
const key = `${programAddress}-${url}`;
const cacheEntry = cachedAnchorProgramPromises[key];
if (cacheEntry === undefined) {
const promise = Program.at(
programAddress,
new Provider(new Connection(url), new NodeWallet(Keypair.generate()), {})
)
.then(program => {
cachedAnchorProgramPromises[key] = {
__type: 'result',
result: program,
};
})
.catch(_ => {
cachedAnchorProgramPromises[key] = { __type: 'result', result: null };
});
cachedAnchorProgramPromises[key] = {
__type: 'promise',
promise,
};
throw promise;
} else if (cacheEntry.__type === 'promise') {
throw cacheEntry.promise;
}
return cacheEntry.result;
}
export type AnchorAccount = {
layout: string;
account: object;
};