-
Notifications
You must be signed in to change notification settings - Fork 27
/
contracts-context.tsx
78 lines (65 loc) · 2.39 KB
/
contracts-context.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
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
/**
* This file was automatically generated by @cosmwasm/ts-codegen@latest.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run the @cosmwasm/ts-codegen generate command to regenerate this file.
*/
import React, { useEffect, useMemo, useRef, useState, useContext } from 'react';
import {
CosmWasmClient,
SigningCosmWasmClient,
} from '@cosmjs/cosmwasm-stargate';
import { IContractsContext, getProviders } from './contractContextProviders';
export interface ContractsConfig {
address: string | undefined;
getCosmWasmClient: () => Promise<CosmWasmClient>;
getSigningCosmWasmClient: () => Promise<SigningCosmWasmClient>;
}
const ContractsContext = React.createContext<IContractsContext | null>(null);
export const ContractsProvider = ({
children,
contractsConfig,
}: {
children: React.ReactNode;
contractsConfig: ContractsConfig;
}) => {
const [cosmWasmClient, setCosmWasmClient] = useState<CosmWasmClient>();
const [signingCosmWasmClient, setSigningCosmWasmClient] =
useState<SigningCosmWasmClient>();
const { address, getCosmWasmClient, getSigningCosmWasmClient } =
contractsConfig;
const prevAddressRef = useRef<string | undefined>(address);
const contracts: IContractsContext = useMemo(() => {
return getProviders(address, cosmWasmClient, signingCosmWasmClient);
}, [address, cosmWasmClient, signingCosmWasmClient]);
useEffect(() => {
const connectSigningCwClient = async () => {
if (address && prevAddressRef.current !== address) {
const signingCosmWasmClient = await getSigningCosmWasmClient();
setSigningCosmWasmClient(signingCosmWasmClient);
} else if (!address) {
setSigningCosmWasmClient(undefined);
}
prevAddressRef.current = address;
};
connectSigningCwClient();
}, [address, getSigningCosmWasmClient]);
useEffect(() => {
const connectCosmWasmClient = async () => {
const cosmWasmClient = await getCosmWasmClient();
setCosmWasmClient(cosmWasmClient);
};
connectCosmWasmClient();
}, [getCosmWasmClient]);
return (
<ContractsContext.Provider value={contracts}>
{children}
</ContractsContext.Provider>
);
};
export const useContracts = () => {
const contracts: IContractsContext = useContext(ContractsContext);
if (contracts === null) {
throw new Error('useContracts must be used within a ContractsProvider');
}
return contracts;
};