-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathERC20Handler.ts
202 lines (178 loc) · 6.53 KB
/
ERC20Handler.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
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
import BigNumber from "bignumber.js";
import { ethers, Overrides } from "ethers";
import { newPromiEvent, PromiEvent } from "../../lib/promiEvent";
import { Asset, DeferHandler, Handler } from "../../types/types";
import { getNetwork, getTransactionConfig } from "../ETH/ethUtils";
import { ERC20ABI } from "./ERC20ABI";
import { ERC20s } from "./ERC20s";
interface ConstructorOptions {}
interface AddressOptions {}
interface BalanceOptions extends AddressOptions {
address?: string;
}
interface TxOptions extends Overrides {
approve?: boolean;
}
const resolveAsset = (network: string, assetIn: Asset): { address: string } => {
if (typeof assetIn !== "object") {
throw new Error("");
}
const asset = assetIn as { address?: string; name?: string };
if (asset.address) {
return { ...asset, address: asset.address };
} else {
const address = ((ERC20s as any)[network] || {})[asset.name || ""];
if (!address) {
throw new Error(
`Unknown ERC20 token ${asset.name || JSON.stringify(asset)}`
);
}
return { ...asset, address };
}
};
export class ERC20Handler
implements
Handler<ConstructorOptions, AddressOptions, BalanceOptions, TxOptions>
{
private readonly network: string;
private readonly sharedState: {
ethSigner: ethers.Signer;
};
private _decimals: { [address: string]: number } = {};
constructor(
_privateKey: string,
network: string,
_options?: ConstructorOptions,
sharedState?: any
) {
this.network = getNetwork(network);
this.sharedState = sharedState;
}
// Returns whether or not this can handle the asset
public readonly handlesAsset = (asset: Asset): boolean => {
return (
typeof asset === "object" &&
asset.hasOwnProperty("type") &&
(asset as { type: string }).type === "ERC20" &&
(asset.hasOwnProperty("address") || asset.hasOwnProperty("name"))
);
};
// Address
public readonly address = async (
asset: Asset,
options: AddressOptions,
deferHandler: DeferHandler
): Promise<string> => deferHandler.address("ETH", options);
// Balance
public readonly getBalance = async (
assetIn: Asset,
options: BalanceOptions,
deferHandler: DeferHandler
): Promise<BigNumber> => {
const asset = resolveAsset(this.network, assetIn);
const decimals = await this.decimals(asset);
return (
await this.getBalanceInSats(asset, options, deferHandler)
).dividedBy(new BigNumber(10).exponentiatedBy(decimals));
};
public readonly getBalanceInSats = async (
assetIn: Asset,
options: BalanceOptions,
deferHandler: DeferHandler
): Promise<BigNumber> => {
const asset = resolveAsset(this.network, assetIn);
const address =
(options && options.address) ||
(deferHandler && (await deferHandler.address("ETH", options))) ||
"";
return new BigNumber(
(await this.getContract(asset).balanceOf(address)).toString()
);
};
// Transfer
// This is re-implemented instead of calling sendSats so that a PromiEvent
// can be returned.
public readonly send = (
to: string,
valueIn: BigNumber,
assetIn: Asset,
options: TxOptions,
deferHandler: DeferHandler
): PromiEvent<string> => {
const asset = resolveAsset(this.network, assetIn);
const promiEvent = newPromiEvent<string>();
(async () => {
const value = valueIn.times(
new BigNumber(10).exponentiatedBy(await this.decimals(asset))
);
const contract = this.getContract(asset);
const config = {
from: await deferHandler.address("ETH"),
...getTransactionConfig(options),
};
let tx: ethers.providers.TransactionResponse;
// tslint:disable: prefer-conditional-expression
if (options.approve) {
// config.gasLimit = contract.estimateGas.approve(to, valueIn.toFixed());
tx = await contract.approve(to, value.toFixed(), config);
} else {
// config.gasLimit = contract.estimateGas.transfer(to, valueIn.toFixed());
tx = await contract.transfer(to, value.toFixed(), config);
}
promiEvent.emit("transactionHash", tx.hash);
await tx.wait();
promiEvent.resolve(tx.hash);
})().catch((error) => {
promiEvent.reject(error);
});
return promiEvent;
};
public readonly sendSats = (
to: string,
valueIn: BigNumber,
assetIn: Asset,
options: TxOptions,
deferHandler: DeferHandler
): PromiEvent<string> => {
const asset = resolveAsset(this.network, assetIn);
const promiEvent = newPromiEvent<string>();
(async () => {
const contract = this.getContract(asset);
const config = {
from: await deferHandler.address("ETH"),
...getTransactionConfig(options),
};
// tslint:disable: prefer-conditional-expression
let tx: ethers.providers.TransactionResponse;
if (options.approve) {
// config.gasLimit = contract.estimateGas.approve(to, valueIn.toFixed());
tx = await contract.approve(to, valueIn.toFixed(), config);
} else {
// config.gasLimit = contract.estimateGas.transfer(to, valueIn.toFixed());
tx = await contract.transfer(to, valueIn.toFixed(), config);
}
promiEvent.emit("transactionHash", tx.hash);
await tx.wait();
promiEvent.resolve(tx.hash);
})().catch((error) => {
promiEvent.reject(error);
});
return promiEvent;
};
private readonly getContract = (asset: Asset) => {
return new ethers.Contract(
resolveAsset(this.network, asset).address,
ERC20ABI,
this.sharedState.ethSigner
);
};
private readonly decimals = async (asset: Asset): Promise<number> => {
const address = resolveAsset(this.network, asset).address;
if (this._decimals[address]) {
return this._decimals[address];
}
return new BigNumber(
(await this.getContract(asset).decimals()).toString()
).toNumber();
};
}