aboutsummaryrefslogtreecommitdiffstats
path: root/src/stores/balance_proxy_allowance_lazy_store.ts
diff options
context:
space:
mode:
Diffstat (limited to 'src/stores/balance_proxy_allowance_lazy_store.ts')
-rw-r--r--src/stores/balance_proxy_allowance_lazy_store.ts54
1 files changed, 54 insertions, 0 deletions
diff --git a/src/stores/balance_proxy_allowance_lazy_store.ts b/src/stores/balance_proxy_allowance_lazy_store.ts
new file mode 100644
index 000000000..e8178b9a9
--- /dev/null
+++ b/src/stores/balance_proxy_allowance_lazy_store.ts
@@ -0,0 +1,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 {
+ protected 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 = {};
+ }
+ protected 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;
+ }
+ protected setBalance(tokenAddress: string, userAddress: string, balance: BigNumber): void {
+ if (_.isUndefined(this.balance[tokenAddress])) {
+ this.balance[tokenAddress] = {};
+ }
+ this.balance[tokenAddress][userAddress] = balance;
+ }
+ protected 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;
+ }
+ protected setProxyAllowance(tokenAddress: string, userAddress: string, proxyAllowance: BigNumber): void {
+ if (_.isUndefined(this.proxyAllowance[tokenAddress])) {
+ this.proxyAllowance[tokenAddress] = {};
+ }
+ this.proxyAllowance[tokenAddress][userAddress] = proxyAllowance;
+ }
+}