-
Notifications
You must be signed in to change notification settings - Fork 6
/
TxDataBuilder.ts
308 lines (269 loc) · 9.86 KB
/
TxDataBuilder.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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
import { type TAbiItem } from '@dequanto/types/TAbi';
import { File } from 'atma-io';
import type { TAccount } from "@dequanto/models/TAccount";
import type { Web3Client } from '@dequanto/clients/Web3Client';
import type { TAddress } from '@dequanto/models/TAddress';
import { $account } from '@dequanto/utils/$account';
import { $bigint } from '@dequanto/utils/$bigint';
import { ITxBuilderNonceOptions, ITxBuilderOptions } from './ITxBuilderOptions';
import { $number } from '@dequanto/utils/$number';
import { TEth } from '@dequanto/models/TEth';
import { $sig } from '@dequanto/utils/$sig';
import { $abiUtils } from '@dequanto/utils/$abiUtils';
import { $hex } from '@dequanto/utils/$hex';
import { $contract } from '@dequanto/utils/$contract';
import { TxNonceManager } from './TxNonceManager';
export class TxDataBuilder {
public abi: TAbiItem[] = null;
constructor(
public client: Web3Client,
public account: { address?: TAddress },
public data: TEth.TxLike,
public config: ITxBuilderOptions = null,
) {
this.data ??= {};
this.data.value = this.data.value ?? 0;
this.data.chainId = client.chainId;
this.abi = config?.abi;
}
setInputDataWithABI(abi: string | TAbiItem, ...params): this {
try {
this.data.data = $abiUtils.serializeMethodCallData(abi, params);
} catch (error) {
error.message = `${JSON.stringify(abi)}\n${error.message}`;
throw error;
}
return this;
}
setValue(value: number | string | bigint): this {
if (value == null) {
return this;
}
if (typeof value === 'number') {
value = $bigint.toWei(value);
}
if (typeof value === 'bigint') {
this.data.value = `0x${value.toString(16)}`;
return this;
}
this.data.value = value;
return this;
}
setConfig (config: ITxBuilderOptions): this {
this.config = config;
return this;
}
async ensureNonce (options?: ITxBuilderNonceOptions) {
if (this.data.nonce != null) {
// was already set
return;
}
await this.setNonce(options);
}
async setNonce(local?: ITxBuilderNonceOptions) {
let opts = {
...(this.config ?? {}),
...(local ?? {})
};
let nonce: bigint;
if (opts.nonce != null) {
if (typeof opts.nonce === 'number' || typeof opts.nonce === 'bigint') {
nonce = BigInt(opts.nonce)
} else if (opts.nonce instanceof TxNonceManager) {
nonce = await opts.nonce.pickNonce(this.client);
} else {
console.error(opts.nonce);
throw new Error(`Invalid nonce ${typeof opts.nonce}`);
}
} else if (opts.overriding) {
nonce = await this.client.getTransactionCount(this.account.address);
// override first pending TX:
} else if (opts.noncePending != null) {
let pendingIndex = BigInt(opts.noncePending) - 1n;
let submitted = await this.client.getTransactionCount(this.account.address);
let next = pendingIndex;
if (next > 0) {
let total = await this.client.getTransactionCount(this.account.address, 'pending');
let pendingCount = total - submitted;
if (pendingCount > 0n && next > pendingCount - 1n) {
next = pendingCount - 1n;
}
}
nonce = submitted + next;
} else {
nonce = await TxNonceManager.loadNonce(this.client, this.account.address);
}
this.data.nonce = Number(nonce);
}
async ensureGas () {
if (this.data.gasPrice == null && this.data.maxFeePerGas == null) {
await this.setGas();
}
}
async setGas({
price,
priceRatio,
gasLimitRatio,
gasLimit,
gasEstimation,
from,
type,
}: {
price?: bigint
priceRatio?: number
gasLimitRatio?: number
gasLimit?: string | number
gasEstimation?: boolean
from?: TAddress
type?: 0 | 1 | 2
} = {}): Promise<this> {
let [ gasPrice, gasUsage ] = await Promise.all([
price != null ?
{ price, base: price, priority: 10n**9n }
: this.client.getGasPrice(),
gasEstimation == null || gasEstimation === true
? this.getGasEstimation(from ?? this.account.address)
: (gasLimit ?? this.client.defaultGasLimit ?? 2_000_000)
]);
let hasPriceRatio = priceRatio != null;
let hasPriceFixed = price != null;
let $priceRatio = 1;
if (hasPriceRatio) {
$priceRatio = priceRatio;
} else if (hasPriceFixed === false) {
$priceRatio = this.client.defaultGasPriceRatio;
}
type ??= this.client.defaultTxType;
if (type === 0 || type === 1) {
let $baseFee = $bigint.multWithFloat(gasPrice.price, $priceRatio);
this.data.gasPrice = $bigint.toHex($baseFee);
this.data.type = type;
} else {
let $baseFee = $bigint.multWithFloat(gasPrice.base ?? gasPrice.price, $priceRatio);
let $priorityFee = gasPrice.priority;
if ($priorityFee == null) {
$priorityFee = await this.client.getGasPriorityFee();
$priorityFee = $bigint.multWithFloat($priorityFee, $priceRatio);
}
this.data.maxFeePerGas = $bigint.toHex($baseFee + $priorityFee);
this.data.maxPriorityFeePerGas = $bigint.toHex($priorityFee);
this.data.type = 2;
}
let hasLimitRatio = gasLimitRatio != null;
let hasLimitFixed = gasLimit != null;
let $gasLimitRatio = 1;
if (hasLimitRatio) {
$gasLimitRatio = gasLimitRatio;
} else if (hasLimitFixed === false) {
$gasLimitRatio = 1.5;
}
this.data.gas = gasLimit ?? Math.floor(Number(gasUsage) * $gasLimitRatio);
return this;
}
increaseGas (ratio: number) {
let { gasPrice, maxFeePerGas } = this.data;
if (gasPrice != null) {
let price = BigInt(gasPrice as any);
let priceNew = $bigint.multWithFloat(price, ratio);
this.data.gasPrice = $bigint.toHex(priceNew);
return;
}
if (maxFeePerGas != null) {
let price = BigInt(maxFeePerGas as any);
let priceNew = $bigint.multWithFloat(price, ratio);
this.data.maxFeePerGas = $bigint.toHex(priceNew);
return;
}
throw new Error(`Not possible to increase the gas price, the price not set yet`);
}
getTxData (client?: Web3Client) {
let txData = {
...this.data,
from: this.account?.address ?? void 0,
chainId: $number.toHex(this.data.chainId ?? client?.chainId ?? this.client?.chainId),
};
for (let key in txData) {
if (key === 'type') {
continue;
}
txData[key] = $hex.ensure(txData[key]);
}
return txData as TEth.TxLike;
}
/** Returns raw signed transaction */
async signToString(privateKey: TEth.EoAccount['key']): Promise<TEth.Hex> {
let address = await $sig.$account.getAddressFromKey(privateKey);
let rpc = await this.client.getRpc();
let txSig = await $sig.signTx(this.data, { address, key: privateKey }, rpc);
return txSig;
}
toJSON () {
return {
account: {
address: this.account?.address,
},
tx: this.data,
config: this.config,
};
}
async save (path: string, additionalProperties?) {
let json = this.toJSON();
await File.writeAsync(path, {
...json,
...(additionalProperties ?? {})
});
}
private async getGasEstimation (from: TAddress) {
try {
return await this.client.getGasEstimation(from, this.data)
} catch (error) {
let message = error.message;
if (error.data?.type != null) {
let data = error.data;
if (error.data.type === `Unknown` && error.data.params) {
let parsed = $contract.parseInputData(error.data.params, this.abi ?? $contract.store.getFlattened());
if (parsed) {
data = parsed;
}
}
message += `\nError: ` + $contract.formatCall(data);
}
let parsed = $contract.parseInputData(this.data.data, this.abi ?? $contract.store.getFlattened());
if (parsed) {
message += `\nMethod: ` + $contract.formatCall(parsed);
}
throw new Error(message);
}
}
static fromJSON (client: Web3Client, account: TAccount, json: {
config: ITxBuilderOptions,
tx: TEth.TxLike,
}) {
let sender = $account.getSender(account);
return new TxDataBuilder(
client,
sender,
json.tx,
json.config
);
}
static normalize(data: Partial<TEth.TxLike>) {
for (let key in data) {
let v = data[key];
if (typeof v === 'string' && /^\d+$/.test(v)) {
data[key] = BigInt(v);
}
}
return data;
}
static getGasPrice (builder: TxDataBuilder): bigint {
let { gasPrice, maxFeePerGas, maxPriorityFeePerGas } = builder.data;
if (gasPrice != null) {
return BigInt(gasPrice as any);
}
if (maxFeePerGas != null) {
return BigInt(maxFeePerGas as any) + BigInt(<any> maxPriorityFeePerGas ?? 0);
}
return null;
}
}