-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathfioEngine.js
More file actions
1570 lines (1438 loc) · 45.2 KB
/
fioEngine.js
File metadata and controls
1570 lines (1438 loc) · 45.2 KB
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// @flow
import { FIOSDK } from '@fioprotocol/fiosdk'
import { EndPoint } from '@fioprotocol/fiosdk/lib/entities/EndPoint'
import { Transactions } from '@fioprotocol/fiosdk/lib/transactions/Transactions'
import { Constants as FioConstants } from '@fioprotocol/fiosdk/lib/utils/constants'
import { bns } from 'biggystring'
import {
type EdgeCurrencyEngineOptions,
type EdgeCurrencyTools,
type EdgeFetchFunction,
type EdgeFreshAddress,
type EdgeSpendInfo,
type EdgeStakingStatus,
type EdgeTransaction,
type EdgeWalletInfo,
InsufficientFundsError
} from 'edge-core-js/types'
import { CurrencyEngine } from '../common/engine.js'
import {
asyncWaterfall,
cleanTxLogs,
getDenomInfo,
promiseAny,
promiseNy,
safeErrorMessage,
shuffleArray,
timeout
} from '../common/utils'
import {
type FioAddress,
type FioDomain,
type FioRequest,
type TxOtherParams,
ACTIONS,
ACTIONS_TO_END_POINT_KEYS,
ACTIONS_TO_FEE_END_POINT_KEYS,
ACTIONS_TO_TX_ACTION_NAME,
BROADCAST_ACTIONS,
DAY_INTERVAL,
DEFAULT_BUNDLED_TXS_AMOUNT,
FEE_ACTION_MAP,
FIO_REQUESTS_TYPES,
HISTORY_NODE_ACTIONS,
HISTORY_NODE_OFFSET,
STAKING_LOCK_PERIOD,
STAKING_REWARD_MEMO
} from './fioConst'
import { fioApiErrorCodes, FioError } from './fioError'
import { FioPlugin } from './fioPlugin.js'
import {
type FioHistoryNodeAction,
type GetFioName,
asFioHistoryNodeAction,
asGetFioBalanceResponse,
asGetFioName,
asHistoryResponse
} from './fioSchema.js'
const ADDRESS_POLL_MILLISECONDS = 10000
const BLOCKCHAIN_POLL_MILLISECONDS = 15000
const TRANSACTION_POLL_MILLISECONDS = 10000
const REQUEST_POLL_MILLISECONDS = 10000
const PROCESS_TX_NAME_LIST = [
ACTIONS_TO_TX_ACTION_NAME[ACTIONS.transferTokens],
ACTIONS_TO_TX_ACTION_NAME[ACTIONS.unStakeFioTokens]
]
type RecentFioFee = {
publicAddress: string,
fee: number
}
type PreparedTrx = {
signatures: string[],
compression: number,
packed_context_free_data: string,
packed_trx: string
}
export class FioEngine extends CurrencyEngine {
fetchCors: EdgeFetchFunction
fioPlugin: FioPlugin
otherMethods: Object
tpid: string
recentFioFee: RecentFioFee
fioSdk: FIOSDK
fioSdkPreparedTrx: FIOSDK
otherData: {
highestTxHeight: number,
fioAddresses: FioAddress[],
fioDomains: FioDomain[],
fioRequests: {
PENDING: FioRequest[],
SENT: FioRequest[]
},
fioRequestsToApprove: { [requestId: string]: any },
srps: number,
stakingRoe: string,
stakingStatus: EdgeStakingStatus
}
localDataDirty() {
this.walletLocalDataDirty = true
}
constructor(
currencyPlugin: FioPlugin,
walletInfo: EdgeWalletInfo,
opts: EdgeCurrencyEngineOptions,
fetchCors: Function,
tpid: string
) {
super(currencyPlugin, walletInfo, opts)
this.fetchCors = fetchCors
this.fioPlugin = currencyPlugin
this.tpid = tpid
this.recentFioFee = { publicAddress: '', fee: 0 }
this.fioSdkInit()
this.otherMethods = {
fioAction: async (actionName: string, params: any): Promise<any> => {
switch (actionName) {
case 'addPublicAddresses':
case 'addPublicAddress':
case 'requestFunds': {
const { fee } = await this.multicastServers(
FEE_ACTION_MAP[actionName].action,
{
[FEE_ACTION_MAP[actionName].propName]:
params[FEE_ACTION_MAP[actionName].propName]
}
)
params.maxFee = fee
break
}
case 'rejectFundsRequest': {
const { fee } = await this.multicastServers(
FEE_ACTION_MAP[actionName].action,
{
[FEE_ACTION_MAP[actionName].propName]:
params[FEE_ACTION_MAP[actionName].propName]
}
)
params.maxFee = fee
const res = await this.multicastServers(actionName, params)
this.removeFioRequest(
params.fioRequestId,
FIO_REQUESTS_TYPES.PENDING
)
this.localDataDirty()
return res
}
case 'cancelFundsRequest': {
const res = await this.multicastServers(actionName, params)
this.removeFioRequest(params.fioRequestId, FIO_REQUESTS_TYPES.SENT)
this.localDataDirty()
return res
}
case 'recordObtData': {
const { fee } = await this.multicastServers(
FEE_ACTION_MAP[actionName].action,
{
[FEE_ACTION_MAP[actionName].propName]:
params[FEE_ACTION_MAP[actionName].propName]
}
)
params.maxFee = fee
if (params.fioRequestId) {
this.otherData.fioRequestsToApprove[params.fioRequestId] = params
this.localDataDirty()
const res = await this.multicastServers(actionName, params)
if (res && res.status === 'sent_to_blockchain') {
delete this.otherData.fioRequestsToApprove[params.fioRequestId]
this.removeFioRequest(
params.fioRequestId,
FIO_REQUESTS_TYPES.PENDING
)
this.localDataDirty()
}
return res
}
break
}
case 'registerFioAddress': {
const { fee } = await this.multicastServers('getFee', {
endPoint: EndPoint[actionName]
})
params.maxFee = fee
const res = await this.multicastServers(actionName, params)
if (
params.ownerPublicKey &&
params.ownerPublicKey !== this.walletInfo.keys.publicKey
) {
return {
feeCollected: res.fee_collected
}
}
const addressAlreadyAdded = this.otherData.fioAddresses.find(
({ name }) => name === params.fioAddress
)
if (!addressAlreadyAdded) {
this.otherData.fioAddresses.push({
name: params.fioAddress
})
this.localDataDirty()
}
return res
}
case 'renewFioDomain': {
const { fee } = await this.multicastServers('getFee', {
endPoint: EndPoint[actionName]
})
params.maxFee = fee
const res = await this.multicastServers(actionName, params)
const renewedDomain = this.otherData.fioDomains.find(
({ name }) => name === params.fioDomain
)
if (renewedDomain) {
renewedDomain.expiration = res.expiration
this.localDataDirty()
}
return res
}
case 'registerFioDomain': {
const { fee } = await this.multicastServers('getFee', {
endPoint: EndPoint.registerFioDomain
})
params.max_fee = fee
// todo: why we use pushTransaction here?
const res = await this.multicastServers('pushTransaction', {
action: 'regdomain',
account: '',
data: {
...params,
tpid
}
})
return res
}
case 'transferFioDomain': {
const res = await this.multicastServers(actionName, params)
const transferredDomainIndex = this.otherData.fioDomains.findIndex(
({ name }) => name === params.fioDomain
)
if (transferredDomainIndex) {
this.otherData.fioDomains.splice(transferredDomainIndex, 1)
this.localDataDirty()
}
return res
}
case 'transferFioAddress': {
const res = await this.multicastServers(actionName, params)
const transferredAddressIndex =
this.otherData.fioAddresses.findIndex(
({ name }) => name === params.fioAddress
)
if (transferredAddressIndex) {
this.otherData.fioAddresses.splice(transferredAddressIndex, 1)
this.localDataDirty()
}
return res
}
case 'addBundledTransactions': {
const fioAddress = this.otherData.fioAddresses.find(
({ name }) => name === params.fioAddress
)
if (fioAddress == null)
throw new FioError('Fio Address is not found in engine')
const res = await this.multicastServers(actionName, params)
fioAddress.bundledTxs += DEFAULT_BUNDLED_TXS_AMOUNT
this.localDataDirty()
return { bundledTxs: fioAddress.bundledTxs, ...res }
}
}
return this.multicastServers(actionName, params)
},
getFee: async (
actionName: string,
fioAddress: string = ''
): Promise<number> => {
const { fee } = await this.multicastServers('getFee', {
endPoint: EndPoint[ACTIONS_TO_FEE_END_POINT_KEYS[actionName]],
fioAddress
})
return fee
},
getFioAddresses: async (): Promise<FioAddress[]> => {
return this.otherData.fioAddresses
},
getFioAddressNames: async (): Promise<string[]> => {
return this.otherData.fioAddresses.map(fioAddress => fioAddress.name)
},
getFioDomains: async (): Promise<FioDomain[]> => {
return this.otherData.fioDomains
},
getFioRequests: async (
type: string,
page: number,
itemsPerPage: number = 50
): Promise<FioRequest[]> => {
const startIndex = itemsPerPage * (page - 1)
const endIndex = itemsPerPage * page
return this.otherData.fioRequests[type]
.sort((a, b) => (a.time_stamp < b.time_stamp ? 1 : -1))
.slice(startIndex, endIndex)
}
}
}
// Normalize date if not exists "Z" parameter
getUTCDate(dateString: string) {
const date = new Date(dateString)
return Date.UTC(
date.getFullYear(),
date.getMonth(),
date.getDate(),
date.getHours(),
date.getMinutes(),
date.getSeconds()
)
}
/*
Unstaked FIO is locked until 7 days after the start of the GMT day for when
the transaction occurred (block-time).
*/
getUnlockDate(txDate: Date) {
const blockTimeBeginingOfGmtDay =
Math.floor(txDate.getTime() / DAY_INTERVAL) * DAY_INTERVAL
return new Date(blockTimeBeginingOfGmtDay + STAKING_LOCK_PERIOD)
}
async loadEngine(
plugin: EdgeCurrencyTools,
walletInfo: EdgeWalletInfo,
opts: EdgeCurrencyEngineOptions
): Promise<void> {
await super.loadEngine(plugin, walletInfo, opts)
if (typeof this.walletInfo.keys.ownerPublicKey !== 'string') {
if (walletInfo.keys.ownerPublicKey) {
this.walletInfo.keys.ownerPublicKey = walletInfo.keys.ownerPublicKey
} else {
const pubKeys = await plugin.derivePublicKey(this.walletInfo)
this.walletInfo.keys.ownerPublicKey = pubKeys.ownerPublicKey
}
}
await this.checkAbiAccounts()
}
fioSdkInit() {
const baseUrl = shuffleArray(
this.currencyInfo.defaultSettings.apiUrls.map(apiUrl => apiUrl)
)[0]
this.fioSdk = new FIOSDK(
this.walletInfo.keys.fioKey,
this.walletInfo.keys.publicKey,
baseUrl,
this.fetchCors,
undefined,
this.tpid
)
this.fioSdkPreparedTrx = new FIOSDK(
this.walletInfo.keys.fioKey,
this.walletInfo.keys.publicKey,
baseUrl,
this.fetchCors,
undefined,
this.tpid,
true
)
}
async checkAbiAccounts(): Promise<void> {
if (Transactions.abiMap.size === FioConstants.rawAbiAccountName.length)
return
await asyncWaterfall(
shuffleArray(
this.currencyInfo.defaultSettings.apiUrls.map(
apiUrl => () => this.loadAbiAccounts(apiUrl)
)
)
)
}
async loadAbiAccounts(apiUrl: string) {
this.setFioSdkBaseUrl(apiUrl)
for (const accountName of FioConstants.rawAbiAccountName) {
if (Transactions.abiMap.get(accountName)) continue
const response = await this.fioSdk.getAbi(accountName)
Transactions.abiMap.set(response.account_name, response)
}
}
setFioSdkBaseUrl(apiUrl: string) {
Transactions.baseUrl = apiUrl
}
// Poll on the blockheight
async checkBlockchainInnerLoop() {
try {
const info = await this.multicastServers('getChainInfo')
const blockHeight = info.head_block_num
if (this.walletLocalData.blockHeight !== blockHeight) {
this.checkDroppedTransactionsThrottled()
this.walletLocalData.blockHeight = blockHeight
this.localDataDirty()
this.currencyEngineCallbacks.onBlockHeightChanged(
this.walletLocalData.blockHeight
)
}
} catch (e) {
this.error(`checkBlockchainInnerLoop Error fetching height: `, e)
}
}
getBalance(options: any): string {
return super.getBalance(options)
}
doInitialBalanceCallback() {
super.doInitialBalanceCallback()
const balanceCurrencyCodes =
this.currencyInfo.defaultSettings.balanceCurrencyCodes
for (const currencyCodeKey in balanceCurrencyCodes) {
try {
this.currencyEngineCallbacks.onBalanceChanged(
balanceCurrencyCodes[currencyCodeKey],
this.walletLocalData.totalBalances[
balanceCurrencyCodes[currencyCodeKey]
] ?? '0'
)
} catch (e) {
this.log.error(
'doInitialBalanceCallback Error for currencyCode',
balanceCurrencyCodes[currencyCodeKey],
e
)
}
}
try {
this.currencyEngineCallbacks.onStakingStatusChanged({
stakedAmounts: [],
...this.otherData.stakingStatus
})
} catch (e) {
this.error(`doInitialBalanceCallback onStakingStatusChanged`, e)
}
}
checkUnStakeTx(otherParams: TxOtherParams): boolean {
return (
otherParams.name ===
ACTIONS_TO_TX_ACTION_NAME[ACTIONS.unStakeFioTokens] ||
(otherParams.data != null &&
otherParams.data.memo === STAKING_REWARD_MEMO)
)
}
updateStakingStatus(
nativeAmount: string,
blockTime: string,
txId: string,
txName: string
): void {
// Might not be necessary, but better to be safe than sorry
if (
this.otherData.stakingStatus == null ||
this.otherData.stakingStatus.stakedAmounts == null
) {
this.otherData.stakingStatus = {
stakedAmounts: []
}
}
const unlockDate = this.getUnlockDate(new Date(this.getUTCDate(blockTime)))
/*
Compare each stakedAmount's unlockDate with the transaction's unlockDate to
find the correct stakedAmount object to place where the transaction.
*/
const stakedAmountIndex =
this.otherData.stakingStatus.stakedAmounts.findIndex(stakedAmount => {
// $FlowFixMe
return stakedAmount.unlockDate?.getTime() === unlockDate.getTime()
})
/*
If no stakedAmount object was found, then insert a new object into the
stakedAmounts array. Insert into the array at the correct index maintaining
a sorting by unlockDate in descending order.
*/
if (stakedAmountIndex < 0) {
// Search for the correct index to insert the new stakedAmount object
const needleIndex = this.otherData.stakingStatus.stakedAmounts.findIndex(
(stakedAmount, index) =>
// $FlowFixMe
unlockDate.getTime() >= (stakedAmount.unlockDate?.getTime() ?? 0)
)
// If needleIndex is -1 (not found), then insert into the end of the array
const index =
needleIndex < 0
? this.otherData.stakingStatus.stakedAmounts.length
: needleIndex
// Insert the new stakedAmount object
this.otherData.stakingStatus.stakedAmounts.splice(index, 0, {
nativeAmount,
unlockDate,
otherParams: {
date: new Date(blockTime),
txs: [{ txId, nativeAmount, blockTime, txName }]
}
})
} else {
const stakedAmount = {
...this.otherData.stakingStatus.stakedAmounts[stakedAmountIndex],
nativeAmount: '0'
}
const addedTxIndex = stakedAmount.otherParams.txs.findIndex(
({ txId: itemTxId, txName: itemTxName }) =>
itemTxId === txId && itemTxName === txName
)
if (addedTxIndex < 0) {
stakedAmount.otherParams.txs.push({
txId,
nativeAmount,
blockTime,
txName
})
} else {
stakedAmount.otherParams.txs[addedTxIndex] = {
txId,
nativeAmount,
blockTime,
txName
}
}
for (const tx of stakedAmount.otherParams.txs) {
stakedAmount.nativeAmount = bns.add(
stakedAmount.nativeAmount,
tx.nativeAmount
)
}
this.otherData.stakingStatus.stakedAmounts[stakedAmountIndex] =
stakedAmount
}
this.localDataDirty()
try {
this.currencyEngineCallbacks.onStakingStatusChanged({
...this.otherData.stakingStatus
})
} catch (e) {
this.error('onStakingStatusChanged error')
}
}
async getStakingStatus(): Promise<EdgeStakingStatus> {
return { ...this.otherData.stakingStatus }
}
processTransaction(
action: FioHistoryNodeAction,
actor: string,
currencyCode: string = this.currencyInfo.currencyCode
): number {
const {
act: { name: trxName, data, account, authorization }
} = action.action_trace
let nativeAmount
let actorSender
let networkFee = '0'
let otherParams: TxOtherParams = {
account,
name: trxName,
authorization,
data,
meta: {}
}
const ourReceiveAddresses = []
if (action.block_num <= this.walletLocalData.otherData.highestTxHeight) {
return action.block_num
}
// Transfer funds transaction
if (PROCESS_TX_NAME_LIST.includes(trxName)) {
nativeAmount = '0'
if (
trxName === ACTIONS_TO_TX_ACTION_NAME[ACTIONS.transferTokens] &&
data.amount != null
) {
nativeAmount = data.amount.toString()
actorSender = data.actor
if (data.payee_public_key === this.walletInfo.keys.publicKey) {
ourReceiveAddresses.push(this.walletInfo.keys.publicKey)
if (actorSender === actor) {
nativeAmount = '0'
}
} else {
nativeAmount = `-${nativeAmount}`
}
}
const index = this.findTransaction(
currencyCode,
action.action_trace.trx_id
)
// Check if fee transaction have already added
if (index > -1) {
const existingTrx = this.transactionList[currencyCode][index]
otherParams = {
...existingTrx.otherParams,
...otherParams,
data: {
...(existingTrx.otherParams != null &&
existingTrx.otherParams.data != null
? existingTrx.otherParams.data
: {}),
...otherParams.data
},
meta: {
...(existingTrx.otherParams != null &&
existingTrx.otherParams.meta != null
? existingTrx.otherParams.meta
: {}),
...otherParams.meta
}
}
if (otherParams.meta.isTransferProcessed) {
return action.block_num
}
if (otherParams.meta.isFeeProcessed) {
if (trxName === ACTIONS_TO_TX_ACTION_NAME[ACTIONS.transferTokens]) {
nativeAmount = bns.sub(nativeAmount, existingTrx.networkFee)
networkFee = existingTrx.networkFee
} else {
nativeAmount = existingTrx.nativeAmount
networkFee = '0'
}
} else {
this.error(
'processTransaction error - existing spend transaction should have isTransferProcessed or isFeeProcessed set'
)
}
}
if (this.checkUnStakeTx(otherParams)) {
this.updateStakingStatus(
data.amount != null ? data.amount.toString() : '0',
action.block_time,
action.action_trace.trx_id,
trxName
)
}
otherParams.meta.isTransferProcessed = true
const edgeTransaction: EdgeTransaction = {
txid: action.action_trace.trx_id,
date: this.getUTCDate(action.block_time) / 1000,
currencyCode,
blockHeight: action.block_num > 0 ? action.block_num : 0,
nativeAmount,
networkFee,
parentNetworkFee: '0',
ourReceiveAddresses,
signedTx: '',
otherParams
}
this.addTransaction(currencyCode, edgeTransaction)
}
// Fee / Reward transaction
if (
trxName === ACTIONS_TO_TX_ACTION_NAME.transfer &&
data.quantity != null
) {
const [amount] = data.quantity.split(' ')
const exchangeAmount = amount.toString()
let denom = getDenomInfo(this.currencyInfo, currencyCode)
if (!denom) {
denom = getDenomInfo(this.currencyInfo, this.currencyInfo.currencyCode)
if (!denom) {
this.error(`Received unsupported currencyCode: ${currencyCode}`)
return 0
}
}
const fioAmount = bns.mul(exchangeAmount, denom.multiplier)
if (data.to === actor) {
nativeAmount = `${fioAmount}`
networkFee = `-${fioAmount}`
} else {
nativeAmount = `-${fioAmount}`
networkFee = fioAmount
}
const index = this.findTransaction(
currencyCode,
action.action_trace.trx_id
)
// Check if transfer transaction have already added
if (index > -1) {
const existingTrx = this.transactionList[currencyCode][index]
otherParams = {
...otherParams,
...existingTrx.otherParams,
data: {
...otherParams.data,
...(existingTrx.otherParams != null &&
existingTrx.otherParams.data != null
? existingTrx.otherParams.data
: {})
},
meta: {
...otherParams.meta,
...(existingTrx.otherParams != null &&
existingTrx.otherParams.meta != null
? existingTrx.otherParams.meta
: {})
}
}
if (otherParams.meta.isFeeProcessed) {
return action.block_num
}
if (otherParams.meta.isTransferProcessed) {
if (data.to !== actor) {
nativeAmount = bns.sub(existingTrx.nativeAmount, networkFee)
} else {
networkFee = '0'
}
} else {
this.error(
'processTransaction error - existing spend transaction should have isTransferProcessed or isFeeProcessed set'
)
}
}
if (this.checkUnStakeTx(otherParams)) {
this.updateStakingStatus(
fioAmount,
action.block_time,
action.action_trace.trx_id,
trxName
)
}
otherParams.meta.isFeeProcessed = true
const edgeTransaction: EdgeTransaction = {
txid: action.action_trace.trx_id,
date: this.getUTCDate(action.block_time) / 1000,
currencyCode,
blockHeight: action.block_num > 0 ? action.block_num : 0,
nativeAmount,
networkFee,
signedTx: '',
ourReceiveAddresses: [],
otherParams
}
this.addTransaction(currencyCode, edgeTransaction)
}
return action.block_num
}
async checkTransactions(historyNodeIndex: number = 0): Promise<boolean> {
if (!this.currencyInfo.defaultSettings.historyNodeUrls[historyNodeIndex])
return false
let newHighestTxHeight = this.walletLocalData.otherData.highestTxHeight
let lastActionSeqNumber = 0
const actor = this.fioSdk.transactions.getActor(
this.walletInfo.keys.publicKey
)
try {
const lastActionObject = await this.requestHistory(
historyNodeIndex,
{
account_name: actor,
pos: -1,
offset: -1
},
HISTORY_NODE_ACTIONS.getActions
)
if (lastActionObject.error && lastActionObject.error.noNodeForIndex) {
// no more history nodes left
return false
}
asHistoryResponse(lastActionObject)
if (lastActionObject.actions.length) {
lastActionSeqNumber = lastActionObject.actions[0].account_action_seq
} else {
// if no transactions at all
return true
}
} catch (e) {
return this.checkTransactions(++historyNodeIndex)
}
let pos = lastActionSeqNumber
let finish = false
while (!finish) {
if (pos < 0) {
break
}
let actionsObject
try {
actionsObject = await this.requestHistory(
historyNodeIndex,
{
account_name: actor,
pos,
offset: -HISTORY_NODE_OFFSET + 1
},
HISTORY_NODE_ACTIONS.getActions
)
if (actionsObject.error && actionsObject.error.noNodeForIndex) {
return false
}
let actions = []
if (actionsObject.actions && actionsObject.actions.length > 0) {
actions = actionsObject.actions
} else {
break
}
for (let i = actions.length - 1; i > -1; i--) {
const action = actions[i]
asFioHistoryNodeAction(action)
const blockNum = this.processTransaction(action, actor)
if (blockNum > newHighestTxHeight) {
newHighestTxHeight = blockNum
} else if (
(blockNum === newHighestTxHeight &&
i === HISTORY_NODE_OFFSET - 1) ||
blockNum < this.walletLocalData.otherData.highestTxHeight
) {
finish = true
break
}
}
if (!actions.length || actions.length < HISTORY_NODE_OFFSET) {
break
}
pos -= HISTORY_NODE_OFFSET
} catch (e) {
return this.checkTransactions(++historyNodeIndex)
}
}
if (newHighestTxHeight > this.walletLocalData.otherData.highestTxHeight) {
this.walletLocalData.otherData.highestTxHeight = newHighestTxHeight
this.localDataDirty()
}
return true
}
async checkTransactionsInnerLoop() {
let transactions
try {
transactions = await this.checkTransactions()
} catch (e) {
this.error('checkTransactionsInnerLoop fetches failed with error: ', e)
return false
}
if (transactions) {
this.tokenCheckTransactionsStatus.FIO = 1
this.updateOnAddressesChecked()
}
if (this.transactionsChangedArray.length > 0) {
this.currencyEngineCallbacks.onTransactionsChanged(
this.transactionsChangedArray
)
this.transactionsChangedArray = []
}
}
async requestHistory(
nodeIndex: number,
params: {
account_name: string,
pos: number,
offset: number
},
uri: string
): Promise<any> {
if (!this.currencyInfo.defaultSettings.historyNodeUrls[nodeIndex])
return { error: { noNodeForIndex: true } }
const apiUrl = this.currencyInfo.defaultSettings.historyNodeUrls[nodeIndex]
const result = await this.fetchCors(`${apiUrl}history/${uri || ''}`, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(params)
})
return result.json()
}
async fioApiRequest(
apiUrl: string,
actionName: string,
params?: any,
returnPreparedTrx: boolean = false
): Promise<any | PreparedTrx> {
const fioSdk = returnPreparedTrx ? this.fioSdkPreparedTrx : this.fioSdk
this.setFioSdkBaseUrl(apiUrl)
let res
try {
switch (actionName) {
case 'getChainInfo':
res = await fioSdk.transactions.getChainInfo()
break
case 'getFioBalance':
res = await fioSdk.genericAction(actionName, params)
asGetFioBalanceResponse(res)
if (res.balance != null && res.balance < 0)
throw new Error('Invalid balance')
break
default:
res = await fioSdk.genericAction(actionName, params)
}
} catch (e) {
// handle FIO API error
if (e.errorCode && fioApiErrorCodes.indexOf(e.errorCode) > -1) {
if (
e.json &&
e.json.fields &&
e.json.fields[0] &&
e.json.fields[0].error
) {
e.message = e.json.fields[0].error
}
res = {
isError: true,
data: {
code: e.errorCode,
message: e.message ?? safeErrorMessage(e),
json: e.json,
list: e.list
}
}
if (e.errorCode !== 404)
this.log(
`fioApiRequest error. actionName: ${actionName} - apiUrl: ${apiUrl} - message: ${JSON.stringify(
e.json
)}`
)
} else {
this.log(
`fioApiRequest error. actionName: ${actionName} - apiUrl: ${apiUrl} - message: `,
e
)
throw e
}
}
return res
}
async executePreparedTrx(
apiUrl: string,
endpoint: string,
preparedTrx: PreparedTrx
) {
this.setFioSdkBaseUrl(apiUrl)
let res
this.warn(
`executePreparedTrx. preparedTrx: ${JSON.stringify(
preparedTrx