1 | import BigNumber from 'bignumber.js'
|
2 | import { AccountInfo } from '../types/accounts'
|
3 | import { BackendInstance, BackendServices } from '../types/backend'
|
4 |
|
5 | import { create as createLogger } from '../common/log'
|
6 | const log = createLogger('randomizer-backend')
|
7 |
|
8 | export interface RandomizerOptions {
|
9 | spread: number
|
10 | variation: number
|
11 | }
|
12 |
|
13 |
|
14 |
|
15 |
|
16 | export default class RandomizerBackend implements BackendInstance {
|
17 | protected spread: number
|
18 | protected variation: number
|
19 | protected getInfo: (accountId: string) => AccountInfo | undefined
|
20 |
|
21 | |
22 |
|
23 |
|
24 |
|
25 |
|
26 | constructor (opts: RandomizerOptions, api: BackendServices) {
|
27 | this.spread = opts.spread || 0
|
28 | this.variation = opts.variation || 0.1
|
29 | this.getInfo = api.getInfo
|
30 |
|
31 |
|
32 | this.variation = Math.min(Math.abs(this.variation), 1)
|
33 |
|
34 | log.warn('(!!!) using the randomizer backend. variation=%s', this.variation)
|
35 | }
|
36 |
|
37 | |
38 |
|
39 |
|
40 | async connect () {
|
41 |
|
42 | }
|
43 |
|
44 | |
45 |
|
46 |
|
47 |
|
48 |
|
49 |
|
50 |
|
51 |
|
52 |
|
53 | async getRate (sourceAccount: string, destinationAccount: string) {
|
54 | const sourceInfo = this.getInfo(sourceAccount)
|
55 | const destinationInfo = this.getInfo(destinationAccount)
|
56 |
|
57 | if (!sourceInfo) {
|
58 | log.error('unable to fetch account info for source account. accountId=%s', sourceAccount)
|
59 | throw new Error('unable to fetch account info for source account. accountId=' + sourceAccount)
|
60 | }
|
61 | if (!destinationInfo) {
|
62 | log.error('unable to fetch account info for destination account. accountId=%s', destinationAccount)
|
63 | throw new Error('unable to fetch account info for destination account. accountId=' + destinationAccount)
|
64 | }
|
65 |
|
66 | const scaleDiff = destinationInfo.assetScale - sourceInfo.assetScale
|
67 |
|
68 |
|
69 |
|
70 |
|
71 |
|
72 |
|
73 | const randomness = Math.max((0.5 - Math.random()) * this.variation * 2, -1).toFixed(5)
|
74 |
|
75 |
|
76 |
|
77 |
|
78 |
|
79 |
|
80 |
|
81 | const rate = new BigNumber(1).plus(randomness).minus(this.spread).shiftedBy(scaleDiff).toPrecision(15)
|
82 |
|
83 | return Number(rate)
|
84 | }
|
85 |
|
86 | |
87 |
|
88 |
|
89 |
|
90 |
|
91 | submitPayment () {
|
92 | return Promise.resolve()
|
93 | }
|
94 | }
|