forked from paraswap/paraswap-dex-lib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsmart-tokens.ts
111 lines (95 loc) · 2.66 KB
/
smart-tokens.ts
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
import { Address, Token } from '../src/types';
export type StateOverride = {
value: Record<string, string>;
};
export type StateSimulateApiOverride = {
storage: {
value: Record<string, string>;
};
};
export type StateOverrides = {
networkID: string;
stateOverrides: Record<Address, StateOverride>;
};
export type AddBalanceFn = (
address: Address,
amount: string,
) => Record<string, string>;
export type AddAllowanceFn = (
address: Address,
spender: Address,
amount: string,
) => Record<string, string>;
const constructAddBalanceFn = (varName: string): AddBalanceFn => {
return (address: Address, amount: string) => {
return {
[`${varName}[${address}]`]: amount,
};
};
};
const constructAddBAllowanceFn = (varName: string): AddAllowanceFn => {
return (address: Address, spender: string, amount: string) => {
return {
[`${varName}[${address}][${spender}]`]: amount,
};
};
};
export const balanceOfFn = constructAddBalanceFn('balanceOf');
export const balancesFn = constructAddBalanceFn('balances');
export const _balancesFn = constructAddBalanceFn('_balances');
export const allowanceFn = constructAddBAllowanceFn('allowance');
export const _allowancesFn = constructAddBAllowanceFn('_allowances');
export const allowedFn = constructAddBAllowanceFn('allowed');
export type SmartTokenParams = Token & {
addBalance?: AddBalanceFn;
addAllowance?: AddAllowanceFn;
};
export class SmartToken {
private value: Record<string, string> = {};
constructor(private params: SmartTokenParams) {
if (!params.addBalance) {
throw new Error(
`${params.address} ${params.symbol} needs to provide addBalance fn`,
);
}
if (!params.addAllowance) {
throw new Error(
`${params.address} ${params.symbol} needs to provide addAllowance fn`,
);
}
}
get address() {
return this.params.address;
}
get token(): Token {
return {
address: this.params.address,
decimals: this.params.decimals,
symbol: this.params.symbol,
type: this.params.type,
};
}
public addBalance(address: Address, amount: string): SmartToken {
const [key, value] = Object.entries(
this.params.addBalance!(address, amount),
)[0];
this.value[key] = value;
return this;
}
public addAllowance(
address: Address,
spender: string,
amount: string,
): SmartToken {
const [key, value] = Object.entries(
this.params.addAllowance!(address, spender, amount),
)[0];
this.value[key] = value;
return this;
}
public applyOverrides(overrides: StateOverrides) {
overrides.stateOverrides[this.params.address] = {
value: this.value,
};
}
}