Skip to content

Commit 5c1317f

Browse files
fix(app): set acc from keplr (#1165)
1 parent 9f2d88c commit 5c1317f

File tree

1 file changed

+32
-3
lines changed

1 file changed

+32
-3
lines changed

src/contexts/signerClient.tsx

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,12 @@ import React, {
55
useMemo,
66
useState,
77
} from 'react';
8+
import _ from 'lodash';
89
import { SigningCyberClient } from '@cybercongress/cyber-js';
910
import configKeplr, { getKeplr } from 'src/utils/keplrUtils';
1011
import { OfflineSigner } from '@cybercongress/cyber-js/build/signingcyberclient';
1112
import { Option } from 'src/types';
12-
import { useAppSelector } from 'src/redux/hooks';
13+
import { useAppDispatch, useAppSelector } from 'src/redux/hooks';
1314
import { Keplr } from '@keplr-wallet/types';
1415
import { addAddressPocket, setDefaultAccount } from 'src/redux/features/pocket';
1516
import { accountsKeplr } from 'src/utils/utils';
@@ -53,11 +54,37 @@ export function useSigningClient() {
5354
}
5455

5556
function SigningClientProvider({ children }: { children: React.ReactNode }) {
56-
const { defaultAccount } = useAppSelector((state) => state.pocket);
57+
const { defaultAccount, accounts } = useAppSelector((state) => state.pocket);
58+
const dispatch = useAppDispatch();
5759
const [signer, setSigner] = useState<SignerClientContextType['signer']>();
5860
const [signerReady, setSignerReady] = useState(false);
5961
const [signingClient, setSigningClient] =
6062
useState<SignerClientContextType['signingClient']>();
63+
const prevAccounts = usePrevious(accounts);
64+
65+
const selectAddress = useCallback(
66+
async (keplr: Keplr) => {
67+
if (!accounts || _.isEqual(prevAccounts, accounts)) {
68+
return;
69+
}
70+
const keyInfo = await keplr.getKey(CHAIN_ID);
71+
72+
const findAccount = Object.keys(accounts).find((key) => {
73+
if (accounts[key].cyber.bech32 === keyInfo.bech32Address) {
74+
return key;
75+
}
76+
77+
return undefined;
78+
});
79+
80+
if (findAccount) {
81+
dispatch(setDefaultAccount({ name: findAccount }));
82+
} else {
83+
dispatch(addAddressPocket(accountsKeplr(keyInfo)));
84+
}
85+
},
86+
[accounts, prevAccounts, dispatch]
87+
);
6188

6289
useEffect(() => {
6390
(async () => {
@@ -76,6 +103,8 @@ function SigningClientProvider({ children }: { children: React.ReactNode }) {
76103
const initSigner = useCallback(async () => {
77104
const windowKeplr = await getKeplr();
78105
if (windowKeplr && windowKeplr.experimentalSuggestChain) {
106+
selectAddress(windowKeplr);
107+
79108
windowKeplr.defaultOptions = {
80109
sign: {
81110
preferNoSetFee: true,
@@ -90,7 +119,7 @@ function SigningClientProvider({ children }: { children: React.ReactNode }) {
90119
setSigner(offlineSigner);
91120
setSigningClient(clientJs);
92121
}
93-
}, []);
122+
}, [selectAddress]);
94123

95124
useEffect(() => {
96125
(async () => {

0 commit comments

Comments
 (0)