-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMCStore.ts
334 lines (300 loc) · 8.99 KB
/
MCStore.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
import BigNumber from 'bignumber.js';
import StellarSdk from 'stellar-sdk';
import { create } from 'zustand';
import { splitCamelCase } from '@/utils';
import {
getNetworkDetails,
getPublicKey,
isConnected,
} from '@stellar/freighter-api';
import * as SorobanClient from 'soroban-client';
import type { MultiCliqueAccount } from '@/types/multiCliqueAccount';
import type { MultisigTransaction } from '@/types/multisigTransaction';
import { getConfig } from '@/services/config';
import type { JwtToken } from '@/types/auth';
import type { ElioConfig } from '@/types/elioConfig';
import {
NETWORK,
NETWORK_PASSPHRASE,
SOROBAN_RPC_ENDPOINT,
XLM_UNITS,
} from '../config/index';
import type { AccountSlice } from './account';
import { createAccountSlice } from './account';
import { contractErrorCodes } from './errors';
export interface MCConfig {
/** Block time in seconds */
blockCreationInterval: number;
networkPassphrase: string;
rpcEndpoint: string;
currentBlockNumber?: number;
}
export interface WalletAccount {
isConnected: boolean;
publicKey: string;
network: string;
networkUrl: string;
networkPassphrase: string;
nativeTokenBalance: BigNumber;
}
export enum TxnResponse {
Success = 'SUCCESS',
Error = 'ERROR',
Warning = 'WARNING',
Cancelled = 'CANCELLED',
}
export interface TxnNotification {
title: string;
message: string;
type: TxnResponse;
timestamp: number;
txnHash?: string;
}
export type ContractName = 'multicliqueCore' | 'multicliquePolicy';
interface PageSlices {
account: AccountSlice;
}
export interface MCState {
currentWalletAccount: WalletAccount | null;
txnNotifications: TxnNotification[];
isTxnProcessing: boolean;
isConnectModalOpen: boolean;
sorobanServer: SorobanClient.Server;
showCongrats: boolean;
currentBlockNumber: number | null;
MCConfig: MCConfig;
multisigAccounts: MultiCliqueAccount[];
multisigTransactions: MultisigTransaction[];
elioConfig: ElioConfig | null;
pages: PageSlices;
jwt: JwtToken | null;
}
export interface MCActions {
updateCurrentWalletAccount: (account: WalletAccount | null) => void;
getWallet: () => void;
addTxnNotification: (notification: TxnNotification) => void;
removeTxnNotification: () => void;
handleErrors: (
errMsg: string,
err?: Error,
contractName?: ContractName
) => void;
fetchNativeTokenBalance: (
publickey: string,
onError?: (err: any) => void
) => Promise<string | null | undefined>;
updateIsConnectModalOpen: (isOpen: boolean) => void;
handleTxnSuccessNotification: (
response: SorobanClient.SorobanRpc.GetTransactionResponse,
successMsg: string,
txnHash?: string
) => void;
updateIsTxnProcessing: (isProcessing: boolean) => void;
updateMultisigAccounts: (accounts: MultiCliqueAccount[]) => void;
updateMultisigTransactions: (transactions: MultisigTransaction[]) => void;
fetchConfig: () => void;
updateJwt: (jwt: JwtToken | null) => void;
}
export interface MCStore extends MCState, MCActions {}
const useMCStore = create<MCStore>((set, get, store) => ({
currentWalletAccount: null,
txnNotifications: [],
isTxnProcessing: false,
isConnectModalOpen: false,
sorobanServer: new SorobanClient.Server(SOROBAN_RPC_ENDPOINT[NETWORK]),
showCongrats: false,
currentBlockNumber: null,
MCConfig: {
blockCreationInterval: 5,
networkPassphrase: NETWORK_PASSPHRASE[NETWORK],
rpcEndpoint: SOROBAN_RPC_ENDPOINT[NETWORK],
},
multisigAccounts: [],
multisigTransactions: [],
elioConfig: null,
jwt: null,
updateCurrentWalletAccount: (account: WalletAccount | null) => {
set({ currentWalletAccount: account });
},
updateIsConnectModalOpen: (isOpen: boolean) => {
set({ isConnectModalOpen: isOpen });
},
handleErrors: (
errMsg: string,
err?: Error | string,
contractName?: ContractName
) => {
set({ isTxnProcessing: false });
// eslint-disable-next-line
console.log(errMsg, err);
let message = '';
if (typeof err === 'object') {
message = err.message;
} else {
message = errMsg;
}
const getErrorCode = (str: string | undefined) => {
if (!str) {
return null;
}
const startMarker = '#';
const errorLines = str.split('\n');
let errorCode: string | null = null;
errorLines.some((line) => {
const sanitizedLine = line.replace(/[()]/g, '');
const start = sanitizedLine.indexOf(startMarker);
if (start !== -1) {
const end = sanitizedLine.indexOf(' ', start);
errorCode =
end === -1
? sanitizedLine.slice(start + 1)
: sanitizedLine.slice(start + 1, end);
return true;
}
return false;
});
return errorCode;
};
const addErrorMsg = (errorCode: string, contract: ContractName) => {
if (errorCode && contractErrorCodes[contract][errorCode]) {
message = `${splitCamelCase(
contractErrorCodes[contract][errorCode]!
)} - ${message}`;
}
};
if (
contractName &&
typeof err === 'string' &&
err.includes('Error(Contract')
) {
const errorCode = getErrorCode(err);
if (errorCode) {
addErrorMsg(errorCode, contractName);
}
}
const newNoti = {
title: TxnResponse.Error,
message,
type: TxnResponse.Error,
timestamp: Date.now(),
};
get().addTxnNotification(newNoti);
},
getWallet: async () => {
// wallet is automatically injected to the window, we just need to get the values
try {
const connected = await isConnected();
const publicKey = await getPublicKey();
if (!publicKey || !connected) {
get().addTxnNotification({
title: 'Please install Freighter Wallet',
message: 'You need to install Freighter Wallet to continue',
type: TxnResponse.Error,
timestamp: Date.now(),
});
}
const networkDetails = await getNetworkDetails();
const nativeBalance = await get().fetchNativeTokenBalance(
publicKey,
(err) => {
throw new Error(err);
}
);
const wallet: WalletAccount = {
isConnected: connected,
network: networkDetails.network,
networkPassphrase: networkDetails.networkPassphrase,
publicKey,
networkUrl: networkDetails.networkUrl,
nativeTokenBalance: nativeBalance
? BigNumber(nativeBalance).multipliedBy(XLM_UNITS)
: BigNumber(0),
};
set({ currentWalletAccount: wallet });
} catch (ex) {
// eslint-disable-next-line
console.error(ex);
}
},
addTxnNotification: (newNotification) => {
const oldTxnNotis = get().txnNotifications;
// add the new noti to first index because we will start displaying notis from the last index
const newNotis = [newNotification, ...oldTxnNotis];
set({ txnNotifications: newNotis });
},
removeTxnNotification: () => {
// first in first out
const currentTxnNotis = get().txnNotifications;
const newNotis = currentTxnNotis.slice(0, -1);
set({ txnNotifications: newNotis });
},
handleTxnSuccessNotification(txnResponse, successMsg, txnHash?) {
// we don't turn off txnIsProcessing here
if (txnResponse.status !== 'SUCCESS') {
return;
}
const noti = {
title: TxnResponse.Success,
message: successMsg,
type: TxnResponse.Success,
timestamp: Date.now(),
txnHash,
};
get().addTxnNotification(noti);
},
fetchNativeTokenBalance: async (
publicKey: string,
onError?: (error: any) => void
) => {
try {
const server = new StellarSdk.Server(
'https://horizon-futurenet.stellar.org/'
);
let account;
const accountErrorMessage = `We're unable to locate your account or it may not have been funded yet.`;
try {
account = await server.loadAccount(publicKey);
if (!account.accountId()) {
get().handleErrors(accountErrorMessage);
return;
}
} catch (ex) {
throw new Error(accountErrorMessage);
}
const nativeBalance = account.balances.filter((balance: any) => {
return balance.asset_type === 'native';
})[0]?.balance;
return nativeBalance;
} catch (err) {
get().handleErrors(err);
if (onError) {
onError(err);
}
return null;
}
},
updateIsTxnProcessing: (isProcessing: boolean) => {
set({ isTxnProcessing: isProcessing });
},
updateMultisigAccounts: (accounts: MultiCliqueAccount[]) => {
set({ multisigAccounts: accounts });
},
updateMultisigTransactions: (transactions: MultisigTransaction[]) => {
set({ multisigTransactions: transactions });
},
fetchConfig: async () => {
try {
const config = await getConfig();
set({ elioConfig: config });
} catch (err) {
get().handleErrors('Error fetching config', err);
}
},
updateJwt: (jwt: JwtToken | null) => {
set({ jwt });
},
pages: {
...createAccountSlice(set, get, store),
},
}));
export default useMCStore;