-
Notifications
You must be signed in to change notification settings - Fork 37
/
smartContract.ts
299 lines (258 loc) · 9.8 KB
/
smartContract.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
import { Address, AddressComputer } from "../address";
import { Compatibility } from "../compatibility";
import { TRANSACTION_MIN_GAS_PRICE } from "../constants";
import { ErrContractHasNoAddress } from "../errors";
import { IAddress, INonce } from "../interface";
import { Transaction } from "../transaction";
import { SmartContractTransactionsFactory } from "../transactionsFactories/smartContractTransactionsFactory";
import { TransactionsFactoryConfig } from "../transactionsFactories/transactionsFactoryConfig";
import { guardValueIsSet } from "../utils";
import { CodeMetadata } from "./codeMetadata";
import { ContractFunction } from "./function";
import { Interaction } from "./interaction";
import {
CallArguments,
DeployArguments,
ICodeMetadata,
ISmartContract,
QueryArguments,
UpgradeArguments,
} from "./interface";
import { NativeSerializer } from "./nativeSerializer";
import { Query } from "./query";
import { EndpointDefinition, TypedValue } from "./typesystem";
interface IAbi {
constructorDefinition: EndpointDefinition;
getEndpoints(): EndpointDefinition[];
getEndpoint(name: string | ContractFunction): EndpointDefinition;
}
/**
* An abstraction for deploying and interacting with Smart Contracts.
*/
export class SmartContract implements ISmartContract {
private address: IAddress = Address.empty();
private abi?: IAbi;
/**
* This object contains a function for each endpoint defined by the contract.
* (a bit similar to web3js's "contract.methods").
*/
public readonly methodsExplicit: { [key: string]: (args?: TypedValue[]) => Interaction } = {};
/**
* This object contains a function for each endpoint defined by the contract.
* (a bit similar to web3js's "contract.methods").
*
* This is an alternative to {@link methodsExplicit}.
* Unlike {@link methodsExplicit}, automatic type inference (wrt. ABI) is applied when using {@link methods}.
*/
public readonly methods: { [key: string]: (args?: any[]) => Interaction } = {};
/**
* Create a SmartContract object by providing its address on the Network.
*/
constructor(options: { address?: IAddress; abi?: IAbi } = {}) {
this.address = options.address || Address.empty();
this.abi = options.abi;
if (this.abi) {
this.setupMethods();
}
}
private setupMethods() {
// eslint-disable-next-line @typescript-eslint/no-this-alias
let contract = this;
let abi = this.getAbi();
for (const definition of abi.getEndpoints()) {
let functionName = definition.name;
// For each endpoint defined by the ABI, we attach a function to the "methods" and "methodsAuto" objects,
// a function that receives typed values as arguments
// and returns a prepared contract interaction.
this.methodsExplicit[functionName] = function (args?: TypedValue[]) {
let func = new ContractFunction(functionName);
let interaction = new Interaction(contract, func, args || []);
return interaction;
};
this.methods[functionName] = function (args?: any[]) {
let func = new ContractFunction(functionName);
// Perform automatic type inference, wrt. the endpoint definition:
let typedArgs = NativeSerializer.nativeToTypedValues(args || [], definition);
let interaction = new Interaction(contract, func, typedArgs || []);
return interaction;
};
}
}
/**
* Sets the address, as on Network.
*/
setAddress(address: IAddress) {
this.address = address;
}
/**
* Gets the address, as on Network.
*/
getAddress(): IAddress {
return this.address;
}
private getAbi(): IAbi {
guardValueIsSet("abi", this.abi);
return this.abi!;
}
getEndpoint(name: string | ContractFunction): EndpointDefinition {
return this.getAbi().getEndpoint(name);
}
/**
* Creates a {@link Transaction} for deploying the Smart Contract to the Network.
*/
deploy({
deployer,
code,
codeMetadata,
initArguments,
value,
gasLimit,
gasPrice,
chainID,
}: DeployArguments): Transaction {
Compatibility.guardAddressIsSetAndNonZero(
deployer,
"'deployer' of SmartContract.deploy()",
"pass the actual address to deploy()",
);
const config = new TransactionsFactoryConfig({ chainID: chainID.valueOf() });
const factory = new SmartContractTransactionsFactory({
config: config,
abi: this.abi,
});
const bytecode = Buffer.from(code.toString(), "hex");
const metadataAsJson = this.getMetadataPropertiesAsObject(codeMetadata);
const transaction = factory.createTransactionForDeploy({
sender: deployer,
bytecode: bytecode,
gasLimit: BigInt(gasLimit.valueOf()),
arguments: initArguments,
isUpgradeable: metadataAsJson.upgradeable,
isReadable: metadataAsJson.readable,
isPayable: metadataAsJson.payable,
isPayableBySmartContract: metadataAsJson.payableBySc,
});
transaction.setChainID(chainID);
transaction.setValue(value ?? 0);
transaction.setGasPrice(gasPrice ?? TRANSACTION_MIN_GAS_PRICE);
return transaction;
}
private getMetadataPropertiesAsObject(codeMetadata?: ICodeMetadata): {
upgradeable: boolean;
readable: boolean;
payable: boolean;
payableBySc: boolean;
} {
let metadata: CodeMetadata;
if (codeMetadata) {
metadata = CodeMetadata.fromBytes(Buffer.from(codeMetadata.toString(), "hex"));
} else {
metadata = new CodeMetadata();
}
const metadataAsJson = metadata.toJSON() as {
upgradeable: boolean;
readable: boolean;
payable: boolean;
payableBySc: boolean;
};
return metadataAsJson;
}
/**
* Creates a {@link Transaction} for upgrading the Smart Contract on the Network.
*/
upgrade({
caller,
code,
codeMetadata,
initArguments,
value,
gasLimit,
gasPrice,
chainID,
}: UpgradeArguments): Transaction {
Compatibility.guardAddressIsSetAndNonZero(
caller,
"'caller' of SmartContract.upgrade()",
"pass the actual address to upgrade()",
);
this.ensureHasAddress();
const config = new TransactionsFactoryConfig({ chainID: chainID.valueOf() });
const factory = new SmartContractTransactionsFactory({
config: config,
abi: this.abi,
});
const bytecode = Uint8Array.from(Buffer.from(code.toString(), "hex"));
const metadataAsJson = this.getMetadataPropertiesAsObject(codeMetadata);
const transaction = factory.createTransactionForUpgrade({
sender: caller,
contract: this.getAddress(),
bytecode: bytecode,
gasLimit: BigInt(gasLimit.valueOf()),
arguments: initArguments,
isUpgradeable: metadataAsJson.upgradeable,
isReadable: metadataAsJson.readable,
isPayable: metadataAsJson.payable,
isPayableBySmartContract: metadataAsJson.payableBySc,
});
transaction.setChainID(chainID);
transaction.setValue(value ?? 0);
transaction.setGasPrice(gasPrice ?? TRANSACTION_MIN_GAS_PRICE);
return transaction;
}
/**
* Creates a {@link Transaction} for calling (a function of) the Smart Contract.
*/
call({ func, args, value, gasLimit, receiver, gasPrice, chainID, caller }: CallArguments): Transaction {
Compatibility.guardAddressIsSetAndNonZero(
caller,
"'caller' of SmartContract.call()",
"pass the actual address to call()",
);
this.ensureHasAddress();
const config = new TransactionsFactoryConfig({ chainID: chainID.valueOf() });
const factory = new SmartContractTransactionsFactory({
config: config,
abi: this.abi,
});
args = args || [];
value = value || 0;
const transaction = factory.createTransactionForExecute({
sender: caller,
contract: receiver ? receiver : this.getAddress(),
function: func.toString(),
gasLimit: BigInt(gasLimit.valueOf()),
arguments: args,
});
transaction.setChainID(chainID);
transaction.setValue(value);
transaction.setGasPrice(gasPrice ?? TRANSACTION_MIN_GAS_PRICE);
return transaction;
}
createQuery({ func, args, value, caller }: QueryArguments): Query {
this.ensureHasAddress();
return new Query({
address: this.getAddress(),
func: func,
args: args,
value: value,
caller: caller,
});
}
private ensureHasAddress() {
if (!this.getAddress().bech32()) {
throw new ErrContractHasNoAddress();
}
}
/**
* Computes the address of a Smart Contract.
* The address is computed deterministically, from the address of the owner and the nonce of the deployment transaction.
*
* @param owner The owner of the Smart Contract
* @param nonce The owner nonce used for the deployment transaction
*/
static computeAddress(owner: IAddress, nonce: INonce): IAddress {
const deployer = Address.fromBech32(owner.bech32());
const addressComputer = new AddressComputer();
return addressComputer.computeContractAddress(deployer, BigInt(nonce.valueOf()));
}
}