/
cosmos.ts
241 lines (203 loc) · 5.59 KB
/
cosmos.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
import {
uint8arrayFromString,
uint8arrayToString,
} from '@lit-protocol/uint8arrays';
import {
AUTH_SIGNATURE_BODY,
LIT_COSMOS_CHAINS,
LIT_ERROR,
LOCAL_STORAGE_KEYS,
} from '@lit-protocol/constants';
import { AuthSig, CosmosWalletType } from '@lit-protocol/types';
import { log, sortedObject, throwError } from '@lit-protocol/misc';
/** ---------- Declaration ---------- */
declare global {
interface Window {
keplr?: any;
leap?: any;
solana?: any;
}
}
/** ---------- Local Interfaces ---------- */
interface CosmosProvider {
provider: any;
account: string;
chainId: string | number;
}
interface CosmosSignDoc {
chain_id: string;
account_number: string;
sequence: string;
fee: {
gas: string;
amount: [];
};
msgs: Array<{
type: string;
value: {
signer: any;
data: any;
};
}>;
memo: string;
}
/** ---------- Local Helpers ---------- */
/**
*
* Get the COSMOS provider from the browser web3 extension
*
* @returns { object || never }
*/
const getProvider = (walletType: CosmosWalletType): any => {
// -- validate
switch (walletType) {
case 'keplr':
if ('keplr' in window) {
return window?.keplr;
}
break;
case 'leap':
if ('leap' in window) {
return window?.leap;
}
}
// -- finally
const message =
'No web3 wallet was found that works with Cosmos. Install a Cosmos wallet or choose another chain';
const error = LIT_ERROR.NO_WALLET_EXCEPTION;
throwError({
message,
errorKind: error.kind,
errorCode: error.name,
});
};
/** ---------- Exports ---------- */
/**
*
* Get cosmos provider details
*
* @property { string } chain
*/
export const connectCosmosProvider = async ({
chain,
walletType,
}: {
chain: string;
walletType: CosmosWalletType;
}): Promise<CosmosProvider> => {
const chainId = LIT_COSMOS_CHAINS[chain].chainId;
const wallet = getProvider(walletType);
// Enabling before using the Cosmos wallet is recommended.
// This method will ask the user whether to allow access if they haven't visited this website.
// Also, it will request that the user unlock the wallet if the wallet is locked.
await wallet.enable(chainId);
const offlineSigner = wallet.getOfflineSigner(chainId);
// You can get the address/public keys by `getAccounts` method.
// It can return the array of address/public key.
// But, currently, Keplr/Leap extension manages only one address/public key pair.
// TODO: (Check if this is still the case 7 Sep 2022)
// This line is needed to set the sender address for SigningCosmosClient.
const accounts = await offlineSigner.getAccounts();
return { provider: wallet, account: accounts[0].address, chainId };
};
/**
*
* Check if the cosmos signature is in the local storage already,
* If not, sign and save the authenticated message
*
* @property { string } chain
* @returns { AuthSig }
*/
export const checkAndSignCosmosAuthMessage = async ({
chain,
walletType,
}: {
chain: string;
walletType: CosmosWalletType;
}): Promise<AuthSig> => {
const connectedCosmosProvider = await connectCosmosProvider({
chain,
walletType,
});
const storageKey = LOCAL_STORAGE_KEYS.AUTH_COSMOS_SIGNATURE;
let authSig: AuthSig | any = localStorage.getItem(storageKey);
// -- if not found in local storage
if (!authSig) {
log('signing auth message because sig is not in local storage');
await signAndSaveAuthMessage(connectedCosmosProvider);
authSig = localStorage.getItem(storageKey);
}
// -- if found in local storage
authSig = JSON.parse(authSig);
// -- validate
if (connectedCosmosProvider.account != authSig.address) {
log(
'signing auth message because account is not the same as the address in the auth sig'
);
await signAndSaveAuthMessage(connectedCosmosProvider);
authSig = localStorage.getItem(storageKey);
authSig = JSON.parse(authSig);
}
log('authSig', authSig);
return authSig;
};
/**
*
* Save and sign the authenticated message
* @param { CosmosProvider } connectedCosmosProvider
*
* @returns { void }
*/
export const signAndSaveAuthMessage = async (
connectedCosmosProvider: CosmosProvider
) => {
const { provider, account, chainId } = connectedCosmosProvider;
const now = new Date().toISOString();
const body = AUTH_SIGNATURE_BODY.replace('{{timestamp}}', now);
const signed = await provider.signArbitrary(chainId, account, body);
//Buffer.from(body).toString("base64");
const data = uint8arrayToString(uint8arrayFromString(body, 'utf8'), 'base64');
const signDoc: CosmosSignDoc = {
chain_id: '',
account_number: '0',
sequence: '0',
fee: {
gas: '0',
amount: [],
},
msgs: [
{
type: 'sign/MsgSignData',
value: {
signer: account,
data,
},
},
],
memo: '',
};
const encodedSignedMsg = serializeSignDoc(signDoc);
const digest = await crypto.subtle.digest('SHA-256', encodedSignedMsg);
const digest_hex = uint8arrayToString(new Uint8Array(digest), 'base16');
let authSig: AuthSig = {
sig: signed.signature,
derivedVia: 'cosmos.signArbitrary',
signedMessage: digest_hex,
address: account,
};
localStorage.setItem(
LOCAL_STORAGE_KEYS.AUTH_COSMOS_SIGNATURE,
JSON.stringify(authSig)
);
};
/**
*
* Turn sorted signDoc object into uint8array
*
* @param { CosmosSignDoc } signDoc
* @returns { Uint8Array } serialized string in uint8array
*/
export const serializeSignDoc = (signDoc: CosmosSignDoc): Uint8Array => {
const sorted = JSON.stringify(sortedObject(signDoc));
return uint8arrayFromString(sorted, 'utf8');
};