-
Notifications
You must be signed in to change notification settings - Fork 55
/
sol.ts
190 lines (155 loc) · 4.83 KB
/
sol.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
import {
AUTH_SIGNATURE_BODY,
EITHER_TYPE,
ELeft,
ERight,
IEither,
LIT_ERROR,
LOCAL_STORAGE_KEYS,
} from '@lit-protocol/constants';
import { IProvider, AuthSig } from '@lit-protocol/types';
import { log, throwError } from '@lit-protocol/misc';
import { getStorageItem } from '@lit-protocol/misc-browser';
// import { toString as uint8arrayToString } from 'uint8arrays';
import {
uint8arrayFromString,
uint8arrayToString,
} from '@lit-protocol/uint8arrays';
/**
*
* Get the Solana provider from the browser web3 extension
*
* @returns { object || never }
*/
const getProvider = (): IEither<any> => {
let resultOrError: IEither<any>;
// -- validate
// The Backpack wallet does not inject a solana object into the window, so we need to check for the backpack object as well.
if ('solana' in window || 'backpack' in window) {
// only check for the solana object on the window, as keplr does not have the same client interface injected into the window.
// @ts-ignore
resultOrError = ERight(window?.solana ?? window?.backpack);
} else {
// -- finally
const message =
'No web3 wallet was found that works with Solana. Install a Solana wallet or choose another chain';
resultOrError = ELeft({
message,
errorKind: LIT_ERROR.NO_WALLET_EXCEPTION.kind,
errorCode: LIT_ERROR.NO_WALLET_EXCEPTION.name,
});
}
return resultOrError;
};
/**
*
* Get Solana provider
*
* @returns { Promise<IProvider | undefined }
*/
export const connectSolProvider = async (): Promise<IProvider | undefined> => {
const providerOrError = getProvider();
if (providerOrError.type === 'ERROR') {
throwError(providerOrError.result);
return;
}
let provider: any = providerOrError.result;
// No need to reconnect if already connected, some wallets such as Backpack throws an error when doing so.
if (!provider.isConnected) {
await provider.connect();
}
const account = provider.publicKey.toBase58();
return { provider, account };
};
/**
*
* Check and sign solana auth message
*
* @returns { AuthSig }
*/
export const checkAndSignSolAuthMessage = async (): Promise<AuthSig> => {
const res = await connectSolProvider();
if (!res) {
log('Failed to connect sol provider');
}
const provider = res?.provider;
const account = res?.account;
const key = LOCAL_STORAGE_KEYS.AUTH_SOL_SIGNATURE;
let authSigOrError = getStorageItem(key);
// let authSig = localStorage.getItem("lit-auth-sol-signature");
let authSig: AuthSig;
// -- case: if unable to get auth from local storage
if (authSigOrError.type === EITHER_TYPE.ERROR) {
log('signing auth message because sig is not in local storage');
await signAndSaveAuthMessage({ provider });
authSigOrError.type = EITHER_TYPE.SUCCESS;
// @ts-ignore
authSigOrError.result = getStorageItem(key);
}
// @ts-ignore
window.test = authSigOrError;
try {
// when it's not in local storage, it's a string
// @ts-ignore
authSig = JSON.parse(authSigOrError.result.result);
} catch (e) {
// when it's in local storage, it's an object
// @ts-ignore
authSig = JSON.parse(authSigOrError.result);
}
// -- if the wallet address isn't the same as the address from local storage
if (account !== authSig.address) {
log(
'signing auth message because account is not the same as the address in the auth sig'
);
await signAndSaveAuthMessage({ provider });
authSigOrError.type = EITHER_TYPE.SUCCESS;
// @ts-ignore
authSigOrError.result = getStorageItem(key);
// @ts-ignore
authSig = JSON.parse(authSigOrError.result);
}
log('authSig', authSig);
return authSig;
};
/**
*
* Sign and save auth signature locally (not saved to the nodes)
*
* @property { any } provider
* @return { Promise<AuthSig | undefined> }
*
*/
export const signAndSaveAuthMessage = async ({
provider,
}: {
provider: any;
}): Promise<AuthSig | undefined> => {
const now = new Date().toISOString();
const body = AUTH_SIGNATURE_BODY.replace('{{timestamp}}', now);
// turn body into Uint8Array
const data = uint8arrayFromString(body, 'utf8');
// const data = naclUtil.encode(body);
let payload: { signature: Uint8Array };
let derivedVia = 'solana.signMessage';
// Backpack wallet expects and returns a different payload from signMessage()
if (provider?.isBackpack) {
const result = await provider.signMessage(data);
payload = { signature: result };
derivedVia = 'backpack.signMessage';
} else {
payload = await provider.signMessage(data, 'utf8');
}
const hexSig = uint8arrayToString(payload.signature, 'base16');
const authSig: AuthSig = {
sig: hexSig,
derivedVia,
signedMessage: body,
address: provider.publicKey.toBase58(),
};
localStorage.setItem(
LOCAL_STORAGE_KEYS.AUTH_SOL_SIGNATURE,
JSON.stringify(authSig)
);
return authSig;
};