aboutsummaryrefslogtreecommitdiffstats
path: root/src/stores/balance_proxy_allowance_lazy_store.ts
blob: 7f392cb82105c991a2d736a655ca83d5addbc91a (plain) (blame)
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
import * as _ from 'lodash';
import {BigNumber} from 'bignumber.js';
import {TokenWrapper} from '../contract_wrappers/token_wrapper';

/**
 * Copy on read store for balances/proxyAllowances of tokens/accounts
 */
export class BalanceAndProxyAllowanceLazyStore {
    private token: TokenWrapper;
    private balance: {
        [tokenAddress: string]: {
            [userAddress: string]: BigNumber,
        },
    };
    private proxyAllowance: {
        [tokenAddress: string]: {
            [userAddress: string]: BigNumber,
        },
    };
    constructor(token: TokenWrapper) {
        this.token = token;
        this.balance = {};
        this.proxyAllowance = {};
    }
    public async getBalanceAsync(tokenAddress: string, userAddress: string): Promise<BigNumber> {
        if (_.isUndefined(this.balance[tokenAddress]) || _.isUndefined(this.balance[tokenAddress][userAddress])) {
            const balance = await this.token.getBalanceAsync(tokenAddress, userAddress);
            this.setBalance(tokenAddress, userAddress, balance);
        }
        const cachedBalance = this.balance[tokenAddress][userAddress];
        return cachedBalance;
    }
    public setBalance(tokenAddress: string, userAddress: string, balance: BigNumber): void {
        if (_.isUndefined(this.balance[tokenAddress])) {
            this.balance[tokenAddress] = {};
        }
        this.balance[tokenAddress][userAddress] = balance;
    }
    public async getProxyAllowanceAsync(tokenAddress: string, userAddress: string): Promise<BigNumber> {
        if (_.isUndefined(this.proxyAllowance[tokenAddress]) ||
            _.isUndefined(this.proxyAllowance[tokenAddress][userAddress])) {
            const proxyAllowance = await this.token.getProxyAllowanceAsync(tokenAddress, userAddress);
            this.setProxyAllowance(tokenAddress, userAddress, proxyAllowance);
        }
        const cachedProxyAllowance = this.proxyAllowance[tokenAddress][userAddress];
        return cachedProxyAllowance;
    }
    public setProxyAllowance(tokenAddress: string, userAddress: string, proxyAllowance: BigNumber): void {
        if (_.isUndefined(this.proxyAllowance[tokenAddress])) {
            this.proxyAllowance[tokenAddress] = {};
        }
        this.proxyAllowance[tokenAddress][userAddress] = proxyAllowance;
    }
}