-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathPredicateConnector.ts
387 lines (322 loc) · 11.1 KB
/
PredicateConnector.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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
import {
type AbiMap,
Address,
type Asset,
type BytesLike,
type ConnectorMetadata,
FuelConnector,
FuelConnectorEventTypes,
type JsonAbi,
type Network,
type Predicate,
type SelectNetworkArguments,
type TransactionRequestLike,
type TransactionResponse,
type Version,
ZeroBytes32,
bn,
calculateGasFee,
concat,
transactionRequestify,
} from 'fuels';
import { PredicateFactory, getMockedSignatureIndex } from './PredicateFactory';
import type { PredicateWalletAdapter } from './PredicateWalletAdapter';
import type {
ConnectorConfig,
Maybe,
MaybeAsync,
PredicateConfig,
PredicateVersion,
PreparedTransaction,
ProviderDictionary,
SignedMessageCustomCurve,
} from './types';
export abstract class PredicateConnector extends FuelConnector {
public connected = false;
public installed = false;
external = true;
public events = FuelConnectorEventTypes;
protected predicateAddress!: string;
protected customPredicate: Maybe<PredicateConfig>;
protected predicateAccount: Maybe<PredicateFactory> = null;
protected subscriptions: Array<() => void> = [];
protected hasProviderSucceeded = true;
private _predicateVersions!: Array<PredicateFactory>;
public abstract name: string;
public abstract metadata: ConnectorMetadata;
public abstract sendTransaction(
address: string,
transaction: TransactionRequestLike,
): Promise<TransactionResponse | string>;
public abstract connect(): Promise<boolean>;
public abstract disconnect(): Promise<boolean>;
protected abstract configProviders(config: ConnectorConfig): MaybeAsync<void>;
protected abstract getWalletAdapter(): PredicateWalletAdapter;
protected abstract getPredicateVersions(): Record<string, PredicateVersion>;
protected abstract getAccountAddress(): MaybeAsync<Maybe<string>>;
protected abstract getProviders(): Promise<ProviderDictionary>;
protected abstract requireConnection(): MaybeAsync<void>;
protected abstract walletAccounts(): Promise<Array<string>>;
abstract signMessageCustomCurve(
_message: string,
): Promise<SignedMessageCustomCurve>;
protected async emitAccountChange(
address: string,
connected = true,
): Promise<void> {
await this.setupPredicate();
this.emit(this.events.connection, connected);
this.emit(
this.events.currentAccount,
this.predicateAccount?.getPredicateAddress(address),
);
this.emit(
this.events.accounts,
this.predicateAccount?.getPredicateAddresses(await this.walletAccounts()),
);
}
protected get predicateVersions(): Array<PredicateFactory> {
if (!this._predicateVersions) {
this._predicateVersions = Object.entries(this.getPredicateVersions())
.map(
([key, pred]) =>
new PredicateFactory(
this.getWalletAdapter(),
pred.predicate,
key,
pred.generatedAt,
),
)
.sort((a, b) => a.sort(b));
}
return this._predicateVersions;
}
protected isAddressPredicate(b: BytesLike, walletAccount: string): boolean {
return this.predicateVersions.some(
(predicate) => predicate.getPredicateAddress(walletAccount) === b,
);
}
protected async getCurrentUserPredicate(): Promise<Maybe<PredicateFactory>> {
const oldFirstPredicateVersions = [...this.predicateVersions].reverse();
for (const predicateInstance of oldFirstPredicateVersions) {
const address = await this.getAccountAddress();
if (!address) {
continue;
}
const { fuelProvider } = await this.getProviders();
const predicate = predicateInstance.build(address, fuelProvider, [1]);
const { balances } = await predicate.getBalances();
if (balances?.length > 0) {
return predicateInstance;
}
}
return null;
}
protected getNewestPredicate(): Maybe<PredicateFactory> {
return this.predicateVersions[0];
}
protected async setupPredicate(): Promise<PredicateFactory> {
if (this.customPredicate?.abi && this.customPredicate?.bin) {
this.predicateAccount = new PredicateFactory(
this.getWalletAdapter(),
this.customPredicate,
'custom',
);
this.predicateAddress = 'custom';
return this.predicateAccount;
}
const predicate =
(await this.getCurrentUserPredicate()) ?? this.getNewestPredicate();
if (!predicate) throw new Error('No predicate found');
this.predicateAddress = predicate.getRoot();
this.predicateAccount = predicate;
return this.predicateAccount;
}
protected subscribe(listener: () => void) {
this.subscriptions.push(listener);
}
protected async getPredicate(
address: string,
transaction: TransactionRequestLike,
): Promise<Predicate> {
if (!(await this.isConnected())) {
throw Error('No connected accounts');
}
if (!this.predicateAccount) {
throw Error('No predicate account found');
}
const walletAccount = this.predicateAccount.getAccountAddress(
address,
await this.walletAccounts(),
);
if (!walletAccount) {
throw Error(`No account found for ${address}`);
}
const transactionRequest = transactionRequestify(transaction);
const predicateSignatureIndex = getMockedSignatureIndex(
transactionRequest.witnesses,
);
const { fuelProvider } = await this.getProviders();
const predicate = this.predicateAccount.build(walletAccount, fuelProvider, [
predicateSignatureIndex,
]);
predicate.connect(fuelProvider);
return predicate;
}
protected async prepareTransaction(
address: string,
transaction: TransactionRequestLike,
): Promise<PreparedTransaction> {
if (!(await this.isConnected())) {
throw Error('No connected accounts');
}
if (!this.predicateAccount) {
throw Error('No predicate account found');
}
const b256Address = Address.fromDynamicInput(address).toString();
const { fuelProvider } = await this.getProviders();
const chainId = await fuelProvider.getChainId();
const walletAccount = this.predicateAccount.getAccountAddress(
b256Address,
await this.walletAccounts(),
);
if (!walletAccount) {
throw Error(`No account found for ${b256Address}`);
}
const transactionRequest = transactionRequestify(transaction);
const transactionFee = transactionRequest.maxFee.toNumber();
const predicateSignatureIndex = getMockedSignatureIndex(
transactionRequest.witnesses,
);
// Create a predicate and set the witness index to call in predicate`
const predicate = this.predicateAccount.build(walletAccount, fuelProvider, [
predicateSignatureIndex,
]);
predicate.connect(fuelProvider);
// To each input of the request, attach the predicate and its data
const requestWithPredicateAttached =
predicate.populateTransactionPredicateData(transactionRequest);
const maxGasUsed =
await this.predicateAccount.getMaxPredicateGasUsed(fuelProvider);
let predictedGasUsedPredicate = bn(0);
requestWithPredicateAttached.inputs.forEach((input) => {
if ('predicate' in input && input.predicate) {
input.witnessIndex = 0;
predictedGasUsedPredicate = predictedGasUsedPredicate.add(maxGasUsed);
}
});
// Add a placeholder for the predicate signature to count on bytes measurement from start. It will be replaced later
requestWithPredicateAttached.witnesses[predicateSignatureIndex] = concat([
ZeroBytes32,
ZeroBytes32,
]);
const { gasPriceFactor } = await predicate.provider.getGasConfig();
const { maxFee, gasPrice } = await predicate.provider.estimateTxGasAndFee({
transactionRequest: requestWithPredicateAttached,
});
const predicateSuccessFeeDiff = calculateGasFee({
gas: predictedGasUsedPredicate,
priceFactor: gasPriceFactor,
gasPrice,
});
const feeWithFat = maxFee.add(predicateSuccessFeeDiff);
const isNeededFatFee = feeWithFat.gt(transactionFee);
if (isNeededFatFee) {
// add more 10 just in case sdk fee estimation is not accurate
requestWithPredicateAttached.maxFee = feeWithFat.add(10);
}
// Attach missing inputs (including estimated predicate gas usage) / outputs to the request
await predicate.provider.estimateTxDependencies(
requestWithPredicateAttached,
);
return {
predicate,
request: requestWithPredicateAttached,
transactionId: requestWithPredicateAttached.getTransactionId(chainId),
account: walletAccount,
transactionRequest,
};
}
public clearSubscriptions() {
if (!this.subscriptions) {
return;
}
this.subscriptions.forEach((listener) => listener());
this.subscriptions = [];
}
public async ping(): Promise<boolean> {
this.getProviders()
.catch(() => {
this.hasProviderSucceeded = false;
})
.then(() => {
this.hasProviderSucceeded = true;
});
return this.hasProviderSucceeded;
}
public async version(): Promise<Version> {
return { app: '0.0.0', network: '0.0.0' };
}
public async isConnected(): Promise<boolean> {
await this.requireConnection();
const accounts = await this.accounts();
return accounts.length > 0;
}
public async accounts(): Promise<Array<string>> {
if (!this.predicateAccount) {
return [];
}
const accs = await this.walletAccounts();
return this.predicateAccount.getPredicateAddresses(accs);
}
public async currentAccount(): Promise<string | null> {
if (!(await this.isConnected())) {
throw Error('No connected accounts');
}
if (!this.predicateAccount) {
throw Error('No predicate account found');
}
const account = await this.getAccountAddress();
return account ? this.predicateAccount.getPredicateAddress(account) : null;
}
public async networks(): Promise<Network[]> {
return [await this.currentNetwork()];
}
public async currentNetwork(): Promise<Network> {
const { fuelProvider } = await this.getProviders();
const chainId = await fuelProvider.getChainId();
return { url: fuelProvider.url, chainId: chainId };
}
public async signMessage(
_address: string,
_message: string,
): Promise<string> {
throw new Error('A predicate account cannot sign messages');
}
public async addAssets(_assets: Asset[]): Promise<boolean> {
throw new Error('Method not implemented.');
}
public async addAsset(_asset: Asset): Promise<boolean> {
throw new Error('Method not implemented.');
}
public async assets(): Promise<Array<Asset>> {
return [];
}
public async addNetwork(_networkUrl: string): Promise<boolean> {
throw new Error('Method not implemented.');
}
public async selectNetwork(
_network: SelectNetworkArguments,
): Promise<boolean> {
throw new Error('Method not implemented.');
}
public async addAbi(_abiMap: AbiMap): Promise<boolean> {
throw new Error('Method not implemented.');
}
public async getAbi(_contractId: string): Promise<JsonAbi> {
throw Error('Cannot get contractId ABI for a predicate');
}
public async hasAbi(_contractId: string): Promise<boolean> {
throw Error('A predicate account cannot have an ABI');
}
}