-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
contract-factory.ts
245 lines (206 loc) · 7.49 KB
/
contract-factory.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
import { Interface } from '@fuel-ts/abi-coder';
import type { JsonAbi, InputValue } from '@fuel-ts/abi-coder';
import type {
Account,
CreateTransactionRequestLike,
Provider,
TransactionResult,
TransactionType,
} from '@fuel-ts/account';
import { CreateTransactionRequest } from '@fuel-ts/account';
import { randomBytes } from '@fuel-ts/crypto';
import { ErrorCode, FuelError } from '@fuel-ts/errors';
import type { BytesLike } from '@fuel-ts/interfaces';
import { Contract } from '@fuel-ts/program';
import type { StorageSlot } from '@fuel-ts/transactions';
import { arrayify, isDefined } from '@fuel-ts/utils';
import { getContractId, getContractStorageRoot, hexlifyWithPrefix } from './util';
/**
* Options for deploying a contract.
*/
export type DeployContractOptions = {
salt?: BytesLike;
storageSlots?: StorageSlot[];
stateRoot?: BytesLike;
configurableConstants?: { [name: string]: unknown };
} & CreateTransactionRequestLike;
export type DeployContractResult<TContract extends Contract = Contract> = {
transactionId: string;
contractId: string;
waitForResult: () => Promise<{
contract: TContract;
transactionResult: TransactionResult<TransactionType.Create>;
}>;
};
/**
* `ContractFactory` provides utilities for deploying and configuring contracts.
*/
export default class ContractFactory {
bytecode: BytesLike;
interface: Interface;
provider!: Provider | null;
account!: Account | null;
/**
* Create a ContractFactory instance.
*
* @param bytecode - The bytecode of the contract.
* @param abi - The contract's ABI (Application Binary Interface).
* @param accountOrProvider - An account or provider to be associated with the factory.
*/
constructor(
bytecode: BytesLike,
abi: JsonAbi | Interface,
accountOrProvider: Account | Provider | null = null
) {
// Force the bytecode to be a byte array
this.bytecode = arrayify(bytecode);
if (abi instanceof Interface) {
this.interface = abi;
} else {
this.interface = new Interface(abi);
}
/**
Instead of using `instanceof` to compare classes, we instead check
if `accountOrProvider` has a `provider` property inside. If yes,
than we assume it's a Wallet.
This approach is safer than using `instanceof` because it
there might be different versions and bundles of the library.
The same is done at:
- ./contract.ts
@see Contract
*/
if (accountOrProvider && 'provider' in accountOrProvider) {
this.provider = accountOrProvider.provider;
this.account = accountOrProvider;
} else {
this.provider = accountOrProvider;
this.account = null;
}
}
/**
* Connect the factory to a provider.
*
* @param provider - The provider to be associated with the factory.
* @returns A new ContractFactory instance.
*/
connect(provider: Provider) {
return new ContractFactory(this.bytecode, this.interface, provider);
}
/**
* Create a transaction request to deploy a contract with the specified options.
*
* @param deployContractOptions - Options for deploying the contract.
* @returns The CreateTransactionRequest object for deploying the contract.
*/
createTransactionRequest(deployContractOptions?: DeployContractOptions) {
const storageSlots = deployContractOptions?.storageSlots
?.map(({ key, value }) => ({
key: hexlifyWithPrefix(key),
value: hexlifyWithPrefix(value),
}))
.sort(({ key: keyA }, { key: keyB }) => keyA.localeCompare(keyB));
const options = {
salt: randomBytes(32),
...deployContractOptions,
storageSlots: storageSlots || [],
};
if (!this.provider) {
throw new FuelError(
ErrorCode.MISSING_PROVIDER,
'Cannot create transaction request without provider'
);
}
const stateRoot = options.stateRoot || getContractStorageRoot(options.storageSlots);
const contractId = getContractId(this.bytecode, options.salt, stateRoot);
const transactionRequest = new CreateTransactionRequest({
bytecodeWitnessIndex: 0,
witnesses: [this.bytecode],
...options,
});
transactionRequest.addContractCreatedOutput(contractId, stateRoot);
return {
contractId,
transactionRequest,
};
}
/**
* Deploy a contract with the specified options.
*
* @param deployContractOptions - Options for deploying the contract.
* @returns A promise that resolves to the deployed contract instance.
*/
async deployContract<TContract extends Contract = Contract>(
deployContractOptions: DeployContractOptions = {}
): Promise<DeployContractResult<TContract>> {
const { contractId, transactionRequest } = await this.prepareDeploy(deployContractOptions);
const account = this.getAccount();
const transactionResponse = await account.sendTransaction(transactionRequest, {
awaitExecution: false,
});
const waitForResult = async () => {
const transactionResult = await transactionResponse.waitForResult<TransactionType.Create>();
const contract = new Contract(contractId, this.interface, account) as TContract;
return { contract, transactionResult };
};
return { waitForResult, contractId, transactionId: transactionResponse.id };
}
/**
* Set configurable constants of the contract with the specified values.
*
* @param configurableConstants - An object containing configurable names and their values.
*/
setConfigurableConstants(configurableConstants: { [name: string]: unknown }) {
try {
const hasConfigurable = Object.keys(this.interface.configurables).length;
if (!hasConfigurable) {
throw new Error('Contract does not have configurables to be set');
}
Object.entries(configurableConstants).forEach(([key, value]) => {
if (!this.interface.configurables[key]) {
throw new Error(`Contract does not have a configurable named: '${key}'`);
}
const { offset } = this.interface.configurables[key];
const encoded = this.interface.encodeConfigurable(key, value as InputValue);
const bytes = arrayify(this.bytecode);
bytes.set(encoded, offset);
this.bytecode = bytes;
});
} catch (err) {
throw new FuelError(
ErrorCode.INVALID_CONFIGURABLE_CONSTANTS,
`Error setting configurable constants on contract: ${(<Error>err).message}.`
);
}
}
private getAccount(): Account {
if (!this.account) {
throw new FuelError(ErrorCode.ACCOUNT_REQUIRED, 'Account not assigned to contract.');
}
return this.account;
}
private async prepareDeploy(deployContractOptions: DeployContractOptions) {
const { configurableConstants } = deployContractOptions;
if (configurableConstants) {
this.setConfigurableConstants(configurableConstants);
}
const { contractId, transactionRequest } = this.createTransactionRequest(deployContractOptions);
const account = this.getAccount();
const txCost = await account.provider.getTransactionCost(transactionRequest);
const { maxFee: setMaxFee } = deployContractOptions;
if (isDefined(setMaxFee)) {
if (txCost.maxFee.gt(setMaxFee)) {
throw new FuelError(
ErrorCode.MAX_FEE_TOO_LOW,
`Max fee '${deployContractOptions.maxFee}' is lower than the required: '${txCost.maxFee}'.`
);
}
} else {
transactionRequest.maxFee = txCost.maxFee;
}
await account.fund(transactionRequest, txCost);
return {
contractId,
transactionRequest,
};
}
}