-
Notifications
You must be signed in to change notification settings - Fork 59
/
Contract.ts
473 lines (462 loc) · 15.6 KB
/
Contract.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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
import BigNumber from 'bignumber.js';
import { snakeToPascal } from '../utils/string';
import {
MIN_GAS_PRICE, Tag, AbiVersion, VmVersion,
} from '../tx/builder/constants';
import {
signAndNotify,
awaitingCompletion,
channelClosed,
channelOpen,
handleUnexpectedMessage,
} from './handlers';
import {
notify, call, SignTx, ChannelState, ChannelOptions, ChannelMessage, ChannelFsm, changeState, emit,
} from './internal';
import { Encoded } from '../utils/encoder';
import { ContractCallReturnType } from '../apis/node';
import { ContractCallObject } from '../contract/Contract';
import Channel from './Base';
import ChannelSpend from './Spend';
import { ChannelError, UnexpectedChannelMessageError } from '../utils/errors';
import { unpackTx } from '../tx/builder';
import { encodeContractAddress } from '../utils/crypto';
function snakeToPascalObjKeys<Type>(obj: object): Type {
return Object.entries(obj).reduce((result, [key, val]) => ({
...result,
[snakeToPascal(key)]: val,
}), {}) as Type;
}
interface CallContractOptions {
amount?: number | BigNumber;
callData?: Encoded.ContractBytearray;
abiVersion?: AbiVersion;
contract?: Encoded.ContractAddress;
returnValue?: any;
gasUsed?: number | BigNumber;
gasPrice?: number | BigNumber;
height?: number;
callerNonce?: number;
log?: any;
returnType?: ContractCallReturnType;
}
interface Contract {
abiVersion: AbiVersion;
active: boolean;
deposit: number | BigNumber;
id: string;
ownerId: string;
referrerIds: string[];
vmVersion: VmVersion;
}
export default class ChannelContract extends ChannelSpend {
static override async initialize(options: ChannelOptions): Promise<ChannelContract> {
return Channel._initialize(new ChannelContract(), options);
}
/**
* Trigger create contract update
*
* The create contract update is creating a contract inside the channel's internal state tree.
* The update is a change to be applied on top of the latest state.
*
* That would create a contract with the poster being the owner of it. Poster commits initially
* a deposit amount of coins to the new contract.
*
* @param options - Options
* @param options.code - Api encoded compiled AEVM byte code
* @param options.callData - Api encoded compiled AEVM call data for the code
* @param options.deposit - Initial amount the owner of the contract commits to it
* @param options.vmVersion - Version of the Virtual Machine
* @param options.abiVersion - Version of the Application Binary Interface
* @param sign - Function which verifies and signs create contract transaction
* @example
* ```js
* channel.createContract({
* code: 'cb_HKtpipK4aCgYb17wZ...',
* callData: 'cb_1111111111111111...',
* deposit: 10,
* vmVersion: 3,
* abiVersion: 1
* }).then(({ accepted, signedTx, address }) => {
* if (accepted) {
* console.log('New contract has been created')
* console.log('Contract address:', address)
* } else {
* console.log('New contract has been rejected')
* }
* })
* ```
*/
async createContract(
{
code, callData, deposit, vmVersion, abiVersion,
}: {
code: Encoded.ContractBytearray;
callData: Encoded.ContractBytearray;
deposit: number | BigNumber;
vmVersion: VmVersion;
abiVersion: AbiVersion;
},
sign: SignTx,
): Promise<{
accepted: boolean; signedTx: Encoded.Transaction; address: Encoded.ContractAddress;
}> {
return this.enqueueAction(() => {
notify(this, 'channels.update.new_contract', {
code,
call_data: callData,
deposit,
vm_version: vmVersion,
abi_version: abiVersion,
});
return {
handler: async (
_: Channel,
message: ChannelMessage,
state: ChannelState,
): Promise<ChannelFsm> => {
if (message.method !== 'channels.sign.update') {
return handleUnexpectedMessage(this, message, state);
}
await signAndNotify(
this,
'channels.update',
message.params.data,
async (tx) => state.sign(tx),
);
return {
handler: (
_2: Channel,
message2: ChannelMessage,
state2: ChannelState,
): ChannelFsm => (
awaitingCompletion(this, message2, state2, () => {
const params = unpackTx(message2.params.data.state, Tag.SignedTx).encodedTx;
if (params.tag !== Tag.ChannelOffChainTx) {
throw new ChannelError(`Tag should be ${Tag[Tag.ChannelOffChainTx]}, got ${Tag[params.tag]} instead`);
}
const addressKey = this._options.role === 'initiator'
? 'initiatorId' : 'responderId';
const owner = this._options[addressKey];
changeState(this, message2.params.data.state);
const address = encodeContractAddress(owner, params.round);
emit(this, 'newContract', address);
state2.resolve({ accepted: true, address, signedTx: message2.params.data.state });
return { handler: channelOpen };
})
),
state,
};
},
state: { sign },
};
});
}
/**
* Trigger call a contract update
*
* The call contract update is calling a preexisting contract inside the channel's
* internal state tree. The update is a change to be applied on top of the latest state.
*
* That would call a contract with the poster being the caller of it. Poster commits
* an amount of coins to the contract.
*
* The call would also create a call object inside the channel state tree. It contains
* the result of the contract call.
*
* It is worth mentioning that the gas is not consumed, because this is an off-chain
* contract call. It would be consumed if it were an on-chain one. This could happen
* if a call with a similar computation amount is to be forced on-chain.
*
* @param options - Options
* @param options.amount - Amount the caller of the contract commits to it
* @param options.callData - ABI encoded compiled AEVM call data for the code
* @param options.contract - Address of the contract to call
* @param options.abiVersion - Version of the ABI
* @param sign - Function which verifies and signs contract call transaction
* @example
* ```js
* channel.callContract({
* contract: 'ct_9sRA9AVE4BYTAkh5RNfJYmwQe1NZ4MErasQLXZkFWG43TPBqa',
* callData: 'cb_1111111111111111...',
* amount: 0,
* abiVersion: 1
* }).then(({ accepted, signedTx }) => {
* if (accepted) {
* console.log('Contract called succesfully')
* } else {
* console.log('Contract call has been rejected')
* }
* })
* ```
*/
async callContract(
{
amount, callData, contract, abiVersion,
}: CallContractOptions,
sign: SignTx,
): Promise<{ accepted: boolean; signedTx: Encoded.Transaction }> {
return this.enqueueAction(() => {
notify(this, 'channels.update.call_contract', {
amount,
call_data: callData,
contract_id: contract,
abi_version: abiVersion,
});
return {
handler: async (
_: Channel,
message: ChannelMessage,
state: ChannelState,
): Promise<ChannelFsm> => {
if (message.method !== 'channels.sign.update') {
return handleUnexpectedMessage(this, message, state);
}
await signAndNotify(
this,
'channels.update',
message.params.data,
async (tx) => state.sign(tx, { updates: message.params.data.updates }),
);
return {
handler: (
_2: Channel,
message2: ChannelMessage,
state2: ChannelState,
): ChannelFsm => (
awaitingCompletion(this, message2, state2, () => {
changeState(this, message2.params.data.state);
state2.resolve({ accepted: true, signedTx: message2.params.data.state });
return { handler: channelOpen };
})
),
state,
};
},
state: { sign },
};
});
}
/**
* Trigger a force progress contract call
* This call is going on-chain
* @param options - Options
* @param options.amount - Amount the caller of the contract commits to it
* @param options.callData - ABI encoded compiled AEVM call data for the code
* @param options.contract - Address of the contract to call
* @param options.abiVersion - Version of the ABI
* @param options.gasPrice=1000000000]
* @param options.gasLimit=1000000]
* @param sign - Function which verifies and signs contract force progress transaction
* @param callbacks - Callbacks
* @example
* ```js
* channel.forceProgress({
* contract: 'ct_9sRA9AVE4BYTAkh5RNfJYmwQe1NZ4MErasQLXZkFWG43TPBqa',
* callData: 'cb_1111111111111111...',
* amount: 0,
* abiVersion: 1,
* gasPrice: 1000005554
* }).then(({ accepted, signedTx }) => {
* if (accepted) {
* console.log('Contract force progress call successful')
* } else {
* console.log('Contract force progress call has been rejected')
* }
* })
* ```
*/
async forceProgress(
{
amount, callData, contract, abiVersion, gasLimit = 1000000, gasPrice = MIN_GAS_PRICE,
}: {
amount: number;
callData: Encoded.ContractBytearray;
contract: Encoded.ContractAddress;
abiVersion: AbiVersion;
gasLimit?: number;
gasPrice?: number;
},
sign: SignTx,
{ onOnChainTx }: Pick<ChannelState, 'onOnChainTx'> = {},
): Promise<{
accepted: boolean;
signedTx: Encoded.Transaction;
tx: Encoded.Transaction | Uint8Array;
}> {
return this.enqueueAction(() => {
notify(this, 'channels.force_progress', {
amount,
call_data: callData,
contract_id: contract,
abi_version: abiVersion,
gas_price: gasPrice,
gas: gasLimit,
});
return {
handler: async (
_: Channel,
message: ChannelMessage,
state: ChannelState,
): Promise<ChannelFsm> => {
if (message.method !== 'channels.sign.force_progress_tx') {
return handleUnexpectedMessage(this, message, state);
}
await signAndNotify(
this,
'channels.force_progress_sign',
message.params.data,
async (tx) => state.sign(tx, { updates: message.params.data.updates }),
);
return {
handler: (
_2: Channel,
message2: ChannelMessage,
state2: ChannelState,
): ChannelFsm => {
if (message2.method === 'channels.on_chain_tx') {
state2.onOnChainTx?.(message2.params.data.tx);
emit(this, 'onChainTx', message2.params.data.tx, {
info: message2.params.data.info,
type: message2.params.data.type,
});
state2.resolve({ accepted: true, tx: message2.params.data.tx });
// TODO: shouldn't be unexpected message in this case
}
return handleUnexpectedMessage(this, message2, state2);
},
state,
};
},
state: { sign, onOnChainTx },
};
});
}
/**
* Call contract using dry-run
*
* In order to get the result of a potential contract call, one might need to
* dry-run a contract call. It takes the exact same arguments as a call would
* and returns the call object.
*
* The call is executed in the channel's state, but it does not impact the state
* whatsoever. It uses as an environment the latest channel's state and the current
* top of the blockchain as seen by the node.
*
* @param options - Options
* @param options.amount - Amount the caller of the contract commits to it
* @param options.callData - ABI encoded compiled AEVM call data for the code
* @param options.contract - Address of the contract to call
* @param options.abiVersion - Version of the ABI
* @example
* ```js
* channel.callContractStatic({
* contract: 'ct_9sRA9AVE4BYTAkh5RNfJYmwQe1NZ4MErasQLXZkFWG43TPBqa',
* callData: 'cb_1111111111111111...',
* amount: 0,
* abiVersion: 1
* }).then(({ returnValue, gasUsed }) => {
* console.log('Returned value:', returnValue)
* console.log('Gas used:', gasUsed)
* })
* ```
*/
async callContractStatic(
{
amount, callData, contract, abiVersion,
}: {
amount: number;
callData: Encoded.ContractBytearray;
contract: Encoded.ContractAddress;
abiVersion: AbiVersion;
},
): Promise<CallContractOptions> {
return snakeToPascalObjKeys(await call(this, 'channels.dry_run.call_contract', {
amount,
call_data: callData,
contract_id: contract,
abi_version: abiVersion,
}));
}
/**
* Get contract call result
*
* The combination of a caller, contract and a round of execution determines the
* contract call. Providing an incorrect set of those results in an error response.
*
* @param options - Options
* @param options.caller - Address of contract caller
* @param options.contract - Address of the contract
* @param options.round - Round when contract was called
* @example
* ```js
* channel.getContractCall({
* caller: 'ak_Y1NRjHuoc3CGMYMvCmdHSBpJsMDR6Ra2t5zjhRcbtMeXXLpLH',
* contract: 'ct_9sRA9AVE4BYTAkh5RNfJYmwQe1NZ4MErasQLXZkFWG43TPBqa',
* round: 3
* }).then(({ returnType, returnValue }) => {
* if (returnType === 'ok') console.log(returnValue)
* })
* ```
*/
async getContractCall(
{ caller, contract, round }: {
caller: Encoded.AccountAddress;
contract: Encoded.ContractAddress;
round: number;
},
): Promise<ContractCallObject> {
return snakeToPascalObjKeys(
await call(this, 'channels.get.contract_call', {
caller_id: caller,
contract_id: contract,
round,
}),
);
}
/**
* Get the latest contract state
*
* @param contract - Address of the contract
* @example
* ```js
* channel.getContractState(
* 'ct_9sRA9AVE4BYTAkh5RNfJYmwQe1NZ4MErasQLXZkFWG43TPBqa'
* ).then(({ contract }) => {
* console.log('deposit:', contract.deposit)
* })
* ```
*/
async getContractState(
contract: Encoded.ContractAddress,
): Promise<{ contract: Contract; contractState: object }> {
const result = await call(this, 'channels.get.contract', { pubkey: contract });
return snakeToPascalObjKeys({
...result,
contract: snakeToPascalObjKeys(result.contract),
});
}
/**
* Clean up all locally stored contract calls
*
* Contract calls are kept locally in order for the participant to be able to look them up.
* They consume memory and in order for the participant to free it - one can prune all messages.
* This cleans up all locally stored contract calls and those will no longer be available for
* fetching and inspection.
*/
async cleanContractCalls(): Promise<void> {
return this.enqueueAction(() => {
notify(this, 'channels.clean_contract_calls');
return {
handler(_: Channel, message: ChannelMessage, state: ChannelState): ChannelFsm {
if (message.method === 'channels.calls_pruned.reply') {
state.resolve();
return { handler: channelOpen };
}
state.reject(new UnexpectedChannelMessageError('Unexpected message received'));
return { handler: channelClosed };
},
};
});
}
}