/
predicate.ts
258 lines (229 loc) · 8.34 KB
/
predicate.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
import type { JsonAbi, InputValue } from '@fuel-ts/abi-coder';
import {
Interface,
INPUT_COIN_FIXED_SIZE,
WORD_SIZE,
calculateVmTxMemory,
SCRIPT_FIXED_SIZE,
} from '@fuel-ts/abi-coder';
import { Address } from '@fuel-ts/address';
import { BaseAssetId } from '@fuel-ts/address/configs';
import { ErrorCode, FuelError } from '@fuel-ts/errors';
import type { AbstractAddress, BytesLike } from '@fuel-ts/interfaces';
import type { BigNumberish } from '@fuel-ts/math';
import { ByteArrayCoder, InputType } from '@fuel-ts/transactions';
import { arrayify, hexlify } from '@fuel-ts/utils';
import { Account } from '../account';
import type { TxParamsType } from '../account';
import { transactionRequestify, BaseTransactionRequest } from '../providers';
import type {
CallResult,
Provider,
ProviderSendTxParams,
TransactionRequest,
TransactionRequestInput,
TransactionRequestLike,
TransactionResponse,
} from '../providers';
import { getPredicateRoot } from './utils';
export type PredicateParams<T = InputValue[]> = {
bytecode: BytesLike;
provider: Provider;
abi?: JsonAbi;
inputData?: T;
configurableConstants?: { [name: string]: unknown };
};
/**
* `Predicate` provides methods to populate transaction data with predicate information and sending transactions with them.
*/
export class Predicate<TInputData extends InputValue[]> extends Account {
bytes: Uint8Array;
predicateData: TInputData = [] as unknown as TInputData;
interface?: Interface;
/**
* Creates an instance of the Predicate class.
*
* @param bytecode - The bytecode of the predicate.
* @param abi - The JSON ABI of the predicate.
* @param provider - The provider used to interact with the blockchain.
* @param inputData - The predicate input data (optional).
* @param configurableConstants - Optional configurable constants for the predicate.
*/
constructor({
bytecode,
abi,
provider,
inputData,
configurableConstants,
}: PredicateParams<TInputData>) {
const { predicateBytes, predicateInterface } = Predicate.processPredicateData(
bytecode,
abi,
configurableConstants
);
const address = Address.fromB256(getPredicateRoot(predicateBytes));
super(address, provider);
this.bytes = predicateBytes;
this.interface = predicateInterface;
if (inputData !== undefined && inputData.length > 0) {
this.predicateData = inputData;
}
}
/**
* Populates the transaction data with predicate data.
*
* @param transactionRequestLike - The transaction request-like object.
* @returns The transaction request with predicate data.
*/
populateTransactionPredicateData(transactionRequestLike: TransactionRequestLike) {
const request = transactionRequestify(transactionRequestLike);
const { policies } = BaseTransactionRequest.getPolicyMeta(request);
request.inputs?.forEach((input: TransactionRequestInput) => {
if (input.type === InputType.Coin && hexlify(input.owner) === this.address.toB256()) {
// eslint-disable-next-line no-param-reassign
input.predicate = this.bytes;
// eslint-disable-next-line no-param-reassign
input.predicateData = this.getPredicateData(policies.length);
}
});
return request;
}
/**
* A helper that creates a transfer transaction request and returns it.
*
* @param destination - The address of the destination.
* @param amount - The amount of coins to transfer.
* @param assetId - The asset ID of the coins to transfer.
* @param txParams - The transaction parameters (gasLimit, gasPrice, maturity).
* @returns A promise that resolves to the prepared transaction request.
*/
async createTransfer(
/** Address of the destination */
destination: AbstractAddress,
/** Amount of coins */
amount: BigNumberish,
/** Asset ID of coins */
assetId: BytesLike = BaseAssetId,
/** Tx Params */
txParams: TxParamsType = {}
): Promise<TransactionRequest> {
const request = await super.createTransfer(destination, amount, assetId, txParams);
return this.populateTransactionPredicateData(request);
}
/**
* Sends a transaction with the populated predicate data.
*
* @param transactionRequestLike - The transaction request-like object.
* @returns A promise that resolves to the transaction response.
*/
sendTransaction(
transactionRequestLike: TransactionRequestLike,
options?: Pick<ProviderSendTxParams, 'awaitExecution'>
): Promise<TransactionResponse> {
const transactionRequest = this.populateTransactionPredicateData(transactionRequestLike);
return super.sendTransaction(transactionRequest, options);
}
/**
* Simulates a transaction with the populated predicate data.
*
* @param transactionRequestLike - The transaction request-like object.
* @returns A promise that resolves to the call result.
*/
simulateTransaction(transactionRequestLike: TransactionRequestLike): Promise<CallResult> {
const transactionRequest = this.populateTransactionPredicateData(transactionRequestLike);
return super.simulateTransaction(transactionRequest);
}
private getPredicateData(policiesLength: number): Uint8Array {
if (!this.predicateData.length) {
return new Uint8Array();
}
const mainFn = this.interface?.functions.main;
const paddedCode = new ByteArrayCoder(this.bytes.length).encode(this.bytes);
const VM_TX_MEMORY = calculateVmTxMemory({
maxInputs: this.provider.getChain().consensusParameters.maxInputs.toNumber(),
});
const OFFSET =
VM_TX_MEMORY +
SCRIPT_FIXED_SIZE +
INPUT_COIN_FIXED_SIZE +
WORD_SIZE +
paddedCode.byteLength +
policiesLength * WORD_SIZE;
return mainFn?.encodeArguments(this.predicateData, OFFSET) || new Uint8Array();
}
/**
* Processes the predicate data and returns the altered bytecode and interface.
*
* @param bytes - The bytes of the predicate.
* @param jsonAbi - The JSON ABI of the predicate.
* @param configurableConstants - Optional configurable constants for the predicate.
* @returns An object containing the new predicate bytes and interface.
*/
private static processPredicateData(
bytes: BytesLike,
jsonAbi?: JsonAbi,
configurableConstants?: { [name: string]: unknown }
) {
let predicateBytes = arrayify(bytes);
let abiInterface: Interface | undefined;
if (jsonAbi) {
abiInterface = new Interface(jsonAbi);
if (abiInterface.functions.main === undefined) {
throw new FuelError(
ErrorCode.ABI_MAIN_METHOD_MISSING,
'Cannot use ABI without "main" function.'
);
}
}
if (configurableConstants && Object.keys(configurableConstants).length) {
predicateBytes = Predicate.setConfigurableConstants(
predicateBytes,
configurableConstants,
abiInterface
);
}
return {
predicateBytes,
predicateInterface: abiInterface,
};
}
/**
* Sets the configurable constants for the predicate.
*
* @param bytes - The bytes of the predicate.
* @param configurableConstants - Configurable constants to be set.
* @param abiInterface - The ABI interface of the predicate.
* @returns The mutated bytes with the configurable constants set.
*/
private static setConfigurableConstants(
bytes: Uint8Array,
configurableConstants: { [name: string]: unknown },
abiInterface?: Interface
) {
const mutatedBytes = bytes;
try {
if (!abiInterface) {
throw new Error(
'Cannot validate configurable constants because the Predicate was instantiated without a JSON ABI'
);
}
if (Object.keys(abiInterface.configurables).length === 0) {
throw new Error('Predicate has no configurable constants to be set');
}
Object.entries(configurableConstants).forEach(([key, value]) => {
if (!abiInterface?.configurables[key]) {
throw new Error(`No configurable constant named '${key}' found in the Predicate`);
}
const { offset } = abiInterface.configurables[key];
const encoded = abiInterface.encodeConfigurable(key, value as InputValue);
mutatedBytes.set(encoded, offset);
});
} catch (err) {
throw new FuelError(
ErrorCode.INVALID_CONFIGURABLE_CONSTANTS,
`Error setting configurable constants: ${(<Error>err).message}.`
);
}
return mutatedBytes;
}
}