-
Notifications
You must be signed in to change notification settings - Fork 76
/
Copy pathcontract-interact.ts
353 lines (313 loc) · 11.9 KB
/
contract-interact.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
import Arweave from 'arweave';
import { CreateTransactionInterface } from 'arweave/node/common';
import Transaction from 'arweave/node/lib/transaction';
import { JWKInterface } from 'arweave/node/lib/wallet';
import { loadContract } from './contract-load';
import { readContract } from './contract-read';
import { execute, ContractInteraction, ContractInteractionResult, ContractHandler } from './contract-step';
import { evalSettings, unpackTags } from './utils';
import { BlockData } from 'arweave/node/blocks';
import SmartWeaveError, { SmartWeaveErrorType } from './errors';
import { SmartWeaveGlobal } from './smartweave-global';
/**
* Writes an interaction on the blockchain.
*
* This simply creates an interaction tx and posts it.
* It does not need to know the current state of the contract.
*
* @param arweave an Arweave client instance
* @param wallet a wallet private key
* @param contractId the Transaction Id of the contract
* @param input the interaction input, will be serialized as Json.
* @param tags an array of tags with name/value as objects.
* @param target if needed to send AR to an address, this is the target.
* @param winstonQty amount of winston to send to the target, if needed.
* @param reward custom reward for txs, if needed.
*/
export async function interactWrite(
arweave: Arweave,
wallet: JWKInterface | 'use_wallet',
contractId: string,
input: any,
tags: { name: string; value: string }[] = [],
target: string = '',
winstonQty: string = '',
reward?: string,
): Promise<string> {
const interactionTx = await createTx(arweave, wallet, contractId, input, tags, target, winstonQty, reward);
const response = await arweave.transactions.post(interactionTx);
if (response.status !== 200) return null;
return interactionTx.id;
}
/**
* Simulates an interaction on the blockchain and returns the simulated transaction.
*
* This simply creates an interaction tx and posts it.
* It does not need to know the current state of the contract.
*
* @param arweave an Arweave client instance
* @param wallet a wallet private key
* @param contractId the Transaction Id of the contract
* @param input the interaction input, will be serialized as Json.
* @param tags an array of tags with name/value as objects.
* @param target if needed to send AR to an address, this is the target.
* @param winstonQty amount of winston to send to the target, if needed.
*/
export async function simulateInteractWrite(
arweave: Arweave,
wallet: JWKInterface,
contractId: string,
input: any,
tags: { name: string; value: string }[] = [],
target: string = '',
winstonQty: string = '',
): Promise<Transaction> {
const interactionTx = await createTx(arweave, wallet, contractId, input, tags, target, winstonQty);
return interactionTx;
}
/**
* This will load a contract to its latest state, and do a dry run of an interaction,
* without writing anything to the chain.
*
* @param arweave an Arweave client instance
* @param wallet a wallet private or public key
* @param contractId the Transaction Id of the contract
* @param input the interaction input.
* @param tags an array of tags with name/value as objects.
* @param target if needed to send AR to an address, this is the target.
* @param winstonQty amount of winston to send to the target, if needed.
* @param myState a locally-generated state variable
* @param fromParam The from address of the transaction
* @param contractInfoParam The loaded contract
*/
export async function interactWriteDryRun(
arweave: Arweave,
wallet: JWKInterface | 'use_wallet',
contractId: string,
input: any,
tags: { name: string; value: string }[] = [],
target: string = '',
winstonQty: string = '',
myState?: any,
fromParam?: any,
contractInfoParam?: {
id: string;
contractSrc: string;
contractSrcTXID: string;
initState: string;
minFee: any;
contractTX: Transaction;
handler: ContractHandler;
swGlobal: SmartWeaveGlobal;
},
): Promise<ContractInteractionResult> {
// tslint:disable-next-line: prefer-const
let { handler, swGlobal, contractSrcTXID } = contractInfoParam || (await loadContract(arweave, contractId));
const latestState = myState || (await readContract(arweave, contractId));
const from = fromParam || (await arweave.wallets.getAddress(wallet));
const settings = evalSettings(latestState);
const evolve: string = latestState.evolve || settings.get('evolve');
let canEvolve: boolean = latestState.canEvolve || settings.get('canEvolve');
// By default, contracts can evolve if there's not an explicit `false`.
if (canEvolve === undefined || canEvolve === null) {
canEvolve = true;
}
if (evolve && /[a-z0-9_-]{43}/i.test(evolve) && canEvolve) {
if (contractSrcTXID !== evolve) {
try {
const contractInfo = await loadContract(arweave, contractId, evolve);
swGlobal = contractInfo.swGlobal;
handler = contractInfo.handler;
contractSrcTXID = evolve;
} catch (e) {
const error: SmartWeaveError = new SmartWeaveError(SmartWeaveErrorType.CONTRACT_NOT_FOUND, {
message: `Contract having txId: ${contractId} not found`,
requestedTxId: contractId,
});
console.log(error);
}
}
}
const interaction: ContractInteraction = {
input,
caller: from,
};
const tx = await createTx(arweave, wallet, contractId, input, tags, target, winstonQty);
const ts = unpackTags(tx);
const currentBlock: BlockData = await arweave.blocks.getCurrent();
swGlobal._activeTx = createDummyTx(tx, from, ts, currentBlock);
return await execute(handler, interaction, latestState);
}
/**
* This will load a contract to its latest state, and do a dry run of an interaction,
* without writing anything to the chain.
*
* @param arweave an Arweave client instance
* @param tx a signed transaction
* @param contractId the Transaction Id of the contract
* @param input the interaction input.
* @param myState a locally-generated state variable
* @param fromParam The from address of the transaction
* @param contractInfoParam The loaded contract
*/
export async function interactWriteDryRunCustom(
arweave: Arweave,
tx: any,
contractId: string,
input: any,
myState: any,
fromParam: any = {},
contractInfoParam: any,
): Promise<ContractInteractionResult> {
// tslint:disable-next-line: prefer-const
let { handler, swGlobal, contractSrcTXID } = contractInfoParam || (await loadContract(arweave, contractId));
const latestState = myState || (await readContract(arweave, contractId));
const from = fromParam;
const settings = evalSettings(latestState);
const evolve: string = latestState.evolve || settings.get('evolve');
let canEvolve: boolean = latestState.canEvolve || settings.get('canEvolve');
// By default, contracts can evolve if there's not an explicit `false`.
if (canEvolve === undefined || canEvolve === null) {
canEvolve = true;
}
if (evolve && /[a-z0-9_-]{43}/i.test(evolve) && canEvolve) {
if (contractSrcTXID !== evolve) {
try {
const contractInfo = await loadContract(arweave, contractId, evolve);
swGlobal = contractInfo.swGlobal;
handler = contractInfo.handler;
contractSrcTXID = evolve;
} catch (e) {
const error: SmartWeaveError = new SmartWeaveError(SmartWeaveErrorType.CONTRACT_NOT_FOUND, {
message: `Contract having txId: ${contractId} not found`,
requestedTxId: contractId,
});
console.log(error);
}
}
}
const interaction: ContractInteraction = {
input,
caller: from,
};
const ts = unpackTags(tx);
const currentBlock: BlockData = await arweave.blocks.getCurrent();
swGlobal._activeTx = createDummyTx(tx, from, ts, currentBlock);
return await execute(handler, interaction, latestState);
}
/**
* This will load a contract to its latest state, and execute a read interaction that
* does not change any state.
*
* @param arweave an Arweave client instance
* @param wallet a wallet private or public key
* @param contractId the Transaction Id of the contract
* @param input the interaction input.
* @param tags an array of tags with name/value as objects.
* @param target if needed to send AR to an address, this is the target.
* @param winstonQty amount of winston to send to the target, if needed.
*/
export async function interactRead(
arweave: Arweave,
wallet: JWKInterface | 'use_wallet' | undefined,
contractId: string,
input: any,
tags: { name: string; value: string }[] = [],
target: string = '',
winstonQty: string = '',
): Promise<any> {
// tslint:disable-next-line: prefer-const
let { handler, swGlobal, contractSrcTXID } = await loadContract(arweave, contractId);
const latestState = await readContract(arweave, contractId);
const from = wallet ? await arweave.wallets.getAddress(wallet) : '';
const settings = evalSettings(latestState);
const evolve: string = latestState.evolve || settings.get('evolve');
let canEvolve: boolean = latestState.canEvolve || settings.get('canEvolve');
// By default, contracts can evolve if there's not an explicit `false`.
if (canEvolve === undefined || canEvolve === null) {
canEvolve = true;
}
if (evolve && /[a-z0-9_-]{43}/i.test(evolve) && canEvolve) {
if (contractSrcTXID !== evolve) {
try {
const contractInfo = await loadContract(arweave, contractId, evolve);
swGlobal = contractInfo.swGlobal;
handler = contractInfo.handler;
contractSrcTXID = evolve;
} catch (e) {
const error: SmartWeaveError = new SmartWeaveError(SmartWeaveErrorType.CONTRACT_NOT_FOUND, {
message: `Contract having txId: ${contractId} not found`,
requestedTxId: contractId,
});
console.log(error);
}
}
}
const interaction: ContractInteraction = {
input,
caller: from,
};
const tx = await createTx(arweave, wallet, contractId, input, tags, target, winstonQty);
const ts = unpackTags(tx);
const currentBlock: BlockData = await arweave.blocks.getCurrent();
swGlobal._activeTx = createDummyTx(tx, from, ts, currentBlock);
const result = await execute(handler, interaction, latestState);
return result.result;
}
async function createTx(
arweave: Arweave,
wallet: JWKInterface | 'use_wallet',
contractId: string,
input: any,
tags: { name: string; value: string }[],
target: string = '',
winstonQty: string = '0',
reward?: string,
): Promise<Transaction> {
const options: Partial<CreateTransactionInterface> = {
data: Math.random().toString().slice(-4),
reward,
};
if (target && target.length) {
options.target = target.toString();
if (winstonQty && +winstonQty > 0) {
options.quantity = winstonQty.toString();
}
}
const interactionTx = await arweave.createTransaction(options, wallet);
if (!input) {
throw new Error(`Input should be a truthy value: ${JSON.stringify(input)}`);
}
if (tags && tags.length) {
for (const tag of tags) {
interactionTx.addTag(tag.name.toString(), tag.value.toString());
}
}
interactionTx.addTag('App-Name', 'SmartWeaveAction');
interactionTx.addTag('App-Version', '0.3.0');
interactionTx.addTag('Contract', contractId);
interactionTx.addTag('Input', JSON.stringify(input));
await arweave.transactions.sign(interactionTx, wallet);
return interactionTx;
}
function createDummyTx(tx: Transaction, from: string, tags: Record<string, string | string[]>, block: BlockData) {
return {
id: tx.id,
owner: {
address: from,
},
recipient: tx.target,
tags,
fee: {
winston: tx.reward,
},
quantity: {
winston: tx.quantity,
},
block: {
id: block.indep_hash,
height: block.height,
timestamp: block.timestamp,
},
};
}