-
Notifications
You must be signed in to change notification settings - Fork 176
/
wallet.js
360 lines (310 loc) · 12.8 KB
/
wallet.js
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
import * as nearlib from 'nearlib'
import sendJson from 'fetch-send-json'
import { findSeedPhraseKey } from 'near-seed-phrase'
import { createClient } from 'near-ledger-js'
import { PublicKey } from 'nearlib/lib/utils'
import { KeyType } from 'nearlib/lib/utils/key_pair'
import { store } from '..'
import { getAccessKeys } from '../actions/account'
import { BN } from 'bn.js'
export const WALLET_CREATE_NEW_ACCOUNT_URL = 'create'
export const WALLET_CREATE_NEW_ACCOUNT_FLOW_URLS = ['create', 'set-recovery', 'setup-seed-phrase', 'recover-account', 'recover-seed-phrase']
export const WALLET_LOGIN_URL = 'login'
export const ACCOUNT_HELPER_URL = process.env.REACT_APP_ACCOUNT_HELPER_URL || 'https://near-contract-helper.onrender.com'
export const IS_MAINNET = process.env.REACT_APP_IS_MAINNET === 'true' || process.env.REACT_APP_IS_MAINNET === 'yes'
export const ACCOUNT_ID_SUFFIX = process.env.REACT_APP_ACCOUNT_ID_SUFFIX || '.test'
const NETWORK_ID = process.env.REACT_APP_NETWORK_ID || 'default'
const CONTRACT_CREATE_ACCOUNT_URL = `${ACCOUNT_HELPER_URL}/account`
export const NODE_URL = process.env.REACT_APP_NODE_URL || 'https://rpc.nearprotocol.com'
const KEY_UNIQUE_PREFIX = '_4:'
const KEY_WALLET_ACCOUNTS = KEY_UNIQUE_PREFIX + 'wallet:accounts_v2'
const KEY_ACTIVE_ACCOUNT_ID = KEY_UNIQUE_PREFIX + 'wallet:active_account_id_v2'
const ACCESS_KEY_FUNDING_AMOUNT = process.env.REACT_APP_ACCESS_KEY_FUNDING_AMOUNT || '100000000'
const ACCOUNT_COST_PER_BYTE = process.env.REACT_APP_ACCOUNT_COST_PER_BYTE || '90900000000000000000'
const ACCOUNT_ID_REGEX = /^(([a-z\d]+[-_])*[a-z\d]+[.@])*([a-z\d]+[-_])*[a-z\d]+$/
export const ACCOUNT_CHECK_TIMEOUT = 500
async function setKeyMeta(publicKey, meta) {
localStorage.setItem(`keyMeta:${publicKey}`, JSON.stringify(meta))
}
async function getKeyMeta(publicKey) {
try {
return JSON.parse(localStorage.getItem(`keyMeta:${publicKey}`)) || {};
} catch (e) {
return {};
}
}
class Wallet {
constructor() {
this.keyStore = new nearlib.keyStores.BrowserLocalStorageKeyStore()
const inMemorySigner = new nearlib.InMemorySigner(this.keyStore)
async function getLedgerKey(accountId) {
let state = store.getState()
if (!state.account.fullAccessKeys) {
await store.dispatch(getAccessKeys(accountId))
state = store.getState()
}
const accessKeys = state.account.fullAccessKeys
if (accessKeys && state.account.accountId === accountId) {
// TODO: Only use Ledger when it's the only available signer for given tx
// TODO: Use network ID
const ledgerKey = accessKeys.find(accessKey => accessKey.meta.type === 'ledger')
if (ledgerKey) {
return PublicKey.from(ledgerKey.public_key)
}
}
return null
}
this.signer = {
async getPublicKey(accountId, networkId) {
return (await getLedgerKey(accountId)) || (await inMemorySigner.getPublicKey(accountId, networkId))
},
async signMessage(message, accountId, networkId) {
if (await getLedgerKey(accountId)) {
// TODO: Use network ID
const client = await createClient()
const signature = await client.sign(message)
return {
signature,
publicKey: await this.getPublicKey(accountId, networkId)
}
}
return inMemorySigner.signMessage(message, accountId, networkId)
}
}
this.connection = nearlib.Connection.fromConfig({
networkId: NETWORK_ID,
provider: { type: 'JsonRpcProvider', args: { url: NODE_URL + '/' } },
signer: this.signer
})
this.accounts = JSON.parse(
localStorage.getItem(KEY_WALLET_ACCOUNTS) || '{}'
)
this.accountId = localStorage.getItem(KEY_ACTIVE_ACCOUNT_ID) || ''
}
save() {
localStorage.setItem(KEY_ACTIVE_ACCOUNT_ID, this.accountId)
localStorage.setItem(KEY_WALLET_ACCOUNTS, JSON.stringify(this.accounts))
}
getAccountId() {
return this.accountId
}
selectAccount(accountId) {
if (!(accountId in this.accounts)) {
return false
}
this.accountId = accountId
this.save()
}
isLegitAccountId(accountId) {
return ACCOUNT_ID_REGEX.test(accountId)
}
async sendMoney(receiverId, amount) {
await this.getAccount(this.accountId).sendMoney(receiverId, amount)
}
redirectToCreateAccount(options = {}, history) {
const param = {
next_url: window.location.search
}
if (options.reset_accounts) {
param.reset_accounts = true
}
// let url = WALLET_CREATE_NEW_ACCOUNT_URL + "?" + $.param(param)
let url =
'/' +
WALLET_CREATE_NEW_ACCOUNT_URL +
'/?' +
Object.keys(param).map(
(p, i) =>
`${i ? '&' : ''}${encodeURIComponent(p)}=${encodeURIComponent(
param[p]
)}`
)
history ? history.push(url) : window.location.replace(url)
}
isEmpty() {
return !this.accounts || !Object.keys(this.accounts).length
}
redirectIfEmpty(history) {
if (this.isEmpty()) {
this.redirectToCreateAccount({}, history)
}
}
async loadAccount() {
if (this.isEmpty()) {
throw new Error('No account.')
}
return {
...await this.getAccount(this.accountId).state(),
accountId: this.accountId,
accounts: this.accounts
}
}
// TODO: Figure out whether wallet should work with any account or current one. Maybe make wallet account specific and switch whole Wallet?
async getAccessKeys() {
if (!this.accountId) return null
const accessKeys = await this.getAccount(this.accountId).getAccessKeys()
return Promise.all(accessKeys.map(async (accessKey) => ({
...accessKey,
meta: await getKeyMeta(accessKey.public_key)
})))
}
async removeAccessKey(publicKey) {
return await this.getAccount(this.accountId).deleteKey(publicKey)
}
async checkAccountAvailable(accountId) {
if (!this.isLegitAccountId(accountId)) {
throw new Error('Invalid username.')
}
if (accountId !== this.accountId) {
return await this.getAccount(accountId).state()
} else {
throw new Error('You are logged into account ' + accountId + ' .')
}
}
async checkNewAccount(accountId) {
if (!this.isLegitAccountId(accountId)) {
throw new Error('Invalid username.')
}
if (accountId.match(/.*[.@].*/)) {
if (!accountId.endsWith(ACCOUNT_ID_SUFFIX)) {
throw new Error('Characters `.` and `@` have special meaning and cannot be used as part of normal account name.');
}
}
if (accountId in this.accounts) {
throw new Error('Account ' + accountId + ' already exists.')
}
let remoteAccount = null
try {
remoteAccount = await this.getAccount(accountId).state()
} catch (e) {
return true
}
if (!!remoteAccount) {
throw new Error('Account ' + accountId + ' already exists.')
}
}
async createNewAccount(accountId, fundingKey, fundingContract) {
this.checkNewAccount(accountId);
const keyPair = nearlib.KeyPair.fromRandom('ed25519');
if (fundingKey && fundingContract) {
await this.createNewAccountLinkdrop(accountId, fundingKey, fundingContract, keyPair);
await this.keyStore.removeKey(NETWORK_ID, fundingContract)
} else {
await sendJson('POST', CONTRACT_CREATE_ACCOUNT_URL, {
newAccountId: accountId,
newAccountPublicKey: keyPair.publicKey.toString()
})
}
await this.saveAndSelectAccount(accountId, keyPair);
}
async createNewAccountLinkdrop(accountId, fundingKey, fundingContract, keyPair) {
const account = this.getAccount(fundingContract);
await this.keyStore.setKey(
NETWORK_ID, fundingContract,
nearlib.KeyPair.fromString(fundingKey)
)
const contract = new nearlib.Contract(account, fundingContract, {
changeMethods: ['create_account_and_claim', 'claim'],
sender: fundingContract
});
const publicKey = keyPair.publicKey.toString().replace('ed25519:', '');
await contract.create_account_and_claim({
new_account_id: accountId,
new_public_key: publicKey
});
}
async saveAndSelectAccount(accountId, keyPair) {
await this.keyStore.setKey(NETWORK_ID, accountId, keyPair)
this.accounts[accountId] = true
this.accountId = accountId
this.save()
}
async addAccessKey(accountId, contractId, publicKey) {
return await this.getAccount(accountId).addKey(
publicKey,
contractId,
'', // methodName
ACCESS_KEY_FUNDING_AMOUNT
)
}
async addLedgerAccessKey(accountId) {
const client = await createClient()
window.client = client
const rawPublicKey = await client.getPublicKey()
const publicKey = new PublicKey(KeyType.ED25519, rawPublicKey)
await setKeyMeta(publicKey, { type: 'ledger' })
return await this.getAccount(accountId).addKey(publicKey)
}
async getAvailableKeys() {
// TODO: Return additional keys (e.g. Ledger)
return [(await this.keyStore.getKey(NETWORK_ID, this.accountId)).publicKey]
}
clearState() {
this.accounts = {}
this.accountId = ''
this.save()
}
getAccount(accountId) {
return new nearlib.Account(this.connection, accountId)
}
getAccountBalance(type) {
const state = store.getState()
const account = state.account;
const costPerByte = new BN(ACCOUNT_COST_PER_BYTE)
const stateStaked = new BN(account.storageUsage).mul(costPerByte)
const staked = new BN(account.locked)
const totalBalance = new BN(account.amount).add(staked)
const availableBalance = totalBalance.sub(staked).sub(stateStaked)
let balance = totalBalance
if (type === 'minimum') {
balance = stateStaked
}
else if (type === 'staked') {
balance = staked
}
else if (type === 'available') {
balance = availableBalance
}
return balance.toString()
}
requestCode(phoneNumber, accountId) {
return sendJson('POST', `${ACCOUNT_HELPER_URL}/account/${phoneNumber}/${accountId}/requestCode`)
}
async signatureFor(accountId) {
const blockNumber = String((await this.connection.provider.status()).sync_info.latest_block_height);
const signed = await this.signer.signMessage(Buffer.from(blockNumber), accountId, NETWORK_ID);
const blockNumberSignature = Buffer.from(signed.signature).toString('base64');
return { blockNumber, blockNumberSignature };
}
async setupRecoveryMessage({ phoneNumber, email, accountId, seedPhrase, publicKey }) {
const account = this.getAccount(accountId)
const accountKeys = await account.getAccessKeys();
if (!accountKeys.some(it => it.public_key.endsWith(publicKey))) {
await account.addKey(publicKey);
}
return sendJson('POST', `${ACCOUNT_HELPER_URL}/account/sendRecoveryMessage`, {
accountId,
email,
phoneNumber,
seedPhrase
});
}
async recoverAccountSeedPhrase(seedPhrase, accountId) {
const account = this.getAccount(accountId)
const accessKeys = await account.getAccessKeys()
const publicKeys = accessKeys.map(it => it.public_key)
const { secretKey } = findSeedPhraseKey(seedPhrase, publicKeys)
if (!secretKey) {
throw new Error(`Cannot find matching public key for account ${accountId}`);
}
const keyPair = nearlib.KeyPair.fromString(secretKey)
await this.saveAndSelectAccount(accountId, keyPair)
}
async signAndSendTransactions(transactions, accountId) {
for (let { receiverId, nonce, blockHash, actions } of transactions) {
const [, signedTransaction] = await nearlib.transactions.signTransaction(receiverId, nonce, actions, blockHash, this.connection.signer, accountId, NETWORK_ID)
await this.connection.provider.sendTransaction(signedTransaction)
}
}
}
export const wallet = new Wallet()