-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathsmartweave-global.ts
371 lines (314 loc) · 10.4 KB
/
smartweave-global.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
/* eslint-disable */
import Arweave from 'arweave';
import { EvaluationOptions } from '../core/modules/StateEvaluator';
import { GQLNodeInterface, GQLTagInterface, VrfData } from './gqlResult';
import { CacheKey, SortKeyCache } from '../cache/SortKeyCache';
import { SortKeyCacheRangeOptions } from '../cache/SortKeyCacheRangeOptions';
import { InteractionState } from '../contract/states/InteractionState';
import { safeGet } from '../utils/utils';
/**
*
* This class is exposed as a global for contracts
* as 'SmartWeave' and provides an API for getting further
* information or using utility and crypto functions from
* inside the contracts execution.
*
* It provides an api:
*
* - SmartWeave.transaction.id
* - SmartWeave.transaction.reward
* - SmartWeave.block.height
* - SmartWeave.block.timestamp
* - etc
*
* and access to some of the arweave utils:
* - SmartWeave.arweave.utils
* - SmartWeave.arweave.crypto
* - SmartWeave.arweave.wallets
* - SmartWeave.arweave.ar
*
* as well as access to the potentially non-deterministic full client:
* - SmartWeave.unsafeClient
*
*/
export type TransactionOrigin = 'L1' | 'L2';
export class SmartWeaveGlobal {
gasUsed: number;
gasLimit: number;
transaction: SWTransaction;
block: SWBlock;
vrf: SWVrf;
evaluationOptions: EvaluationOptions;
arweave: Pick<Arweave, 'ar' | 'wallets' | 'utils' | 'crypto'>;
contract: {
id: string;
owner: string;
};
unsafeClient: Arweave;
baseArweaveUrl: string;
safeArweaveGet: (input: RequestInfo | URL, init?: RequestInit) => Promise<unknown>;
contracts: {
readContractState: (contractId: string) => Promise<any>;
viewContractState: (contractId: string, input: any) => Promise<any>;
write: (contractId: string, input: any) => Promise<any>;
refreshState: () => Promise<any>;
};
extensions: any;
_activeTx?: GQLNodeInterface;
caller?: string;
kv: KV;
constructor(
arweave: Arweave,
contract: { id: string; owner: string },
evaluationOptions: EvaluationOptions,
interactionState: InteractionState,
storage: SortKeyCache<any> | null
) {
this.gasUsed = 0;
this.gasLimit = Number.MAX_SAFE_INTEGER;
this.unsafeClient = arweave;
this.arweave = {
ar: arweave.ar,
utils: arweave.utils,
wallets: arweave.wallets,
crypto: arweave.crypto
};
this.baseArweaveUrl = `${arweave.api.config.protocol}://${arweave.api.config.host}:${arweave.api.config.port}`;
this.safeArweaveGet = async function (query: string) {
return safeGet(`${this.baseArweaveUrl}${query}`);
};
this.evaluationOptions = evaluationOptions;
this.contract = contract;
this.transaction = new SWTransaction(this);
this.block = new SWBlock(this);
this.contracts = {
readContractState: (contractId: string, height?: number, returnValidity?: boolean) => {
throw new Error('Not implemented - should be set by HandlerApi implementor');
},
viewContractState: (contractId: string, input: any) => {
throw new Error('Not implemented - should be set by HandlerApi implementor');
},
write: (contractId: string, input: any, throwOnError?: boolean) => {
throw new Error('Not implemented - should be set by HandlerApi implementor');
},
refreshState: () => {
throw new Error('Not implemented - should be set by HandlerApi implementor');
}
};
this.vrf = new SWVrf(this);
this.useGas = this.useGas.bind(this);
this.getBalance = this.getBalance.bind(this);
this.extensions = {};
this.kv = new KV(storage, interactionState, this.transaction, this.contract.id);
}
useGas(gas: number) {
if (gas < 0) {
throw new Error(`[RE:GNE] Gas number exception - gas < 0.`);
}
this.gasUsed += gas;
if (this.gasUsed > this.gasLimit) {
throw new Error(`[RE:OOG] Out of gas! Used: ${this.gasUsed}, limit: ${this.gasLimit}`);
}
}
async getBalance(address: string, height?: number): Promise<string> {
if (!this._activeTx) {
throw new Error('Cannot read balance - active tx is not set.');
}
if (!this.block.height) {
throw new Error('Cannot read balance - block height not set.');
}
const effectiveHeight = height || this.block.height;
// http://nyc-1.dev.arweave.net:1984/block/height/914387/wallet/M-mpNeJbg9h7mZ-uHaNsa5jwFFRAq0PsTkNWXJ-ojwI/balance
return await fetch(
`${this.evaluationOptions.walletBalanceUrl}block/height/${effectiveHeight}/wallet/${address}/balance`
)
.then((res) => {
return res.ok ? res.text() : Promise.reject(res);
})
.catch((error) => {
throw new Error(`Unable to read wallet balance. ${error.status}. ${error.body?.message}`);
});
}
}
// tslint:disable-next-line: max-classes-per-file
export class SWTransaction {
constructor(private readonly smartWeaveGlobal: SmartWeaveGlobal) {}
get id() {
if (!this.smartWeaveGlobal._activeTx) {
throw new Error('No current Tx');
}
return this.smartWeaveGlobal._activeTx.id;
}
get owner() {
if (!this.smartWeaveGlobal._activeTx) {
throw new Error('No current Tx');
}
return this.smartWeaveGlobal._activeTx.owner.address;
}
get target() {
if (!this.smartWeaveGlobal._activeTx) {
throw new Error('No current Tx');
}
return this.smartWeaveGlobal._activeTx.recipient;
}
get tags(): GQLTagInterface[] {
if (!this.smartWeaveGlobal._activeTx) {
throw new Error('No current Tx');
}
return this.smartWeaveGlobal._activeTx.tags;
}
get sortKey(): string {
if (!this.smartWeaveGlobal._activeTx) {
throw new Error('No current Tx');
}
return this.smartWeaveGlobal._activeTx.sortKey;
}
get dryRun(): boolean {
if (!this.smartWeaveGlobal._activeTx) {
throw new Error('No current Tx');
}
return this.smartWeaveGlobal._activeTx.dry === true;
}
get quantity() {
if (!this.smartWeaveGlobal._activeTx) {
throw new Error('No current Tx');
}
return this.smartWeaveGlobal._activeTx.quantity.winston;
}
get reward() {
if (!this.smartWeaveGlobal._activeTx) {
throw new Error('No current Tx');
}
return this.smartWeaveGlobal._activeTx.fee.winston;
}
get origin(): TransactionOrigin {
if (!this.smartWeaveGlobal._activeTx) {
throw new Error('No current Tx');
}
return this.smartWeaveGlobal._activeTx.source === 'redstone-sequencer' ? 'L2' : 'L1';
}
}
// tslint:disable-next-line: max-classes-per-file
export class SWBlock {
constructor(private readonly smartWeaveGlobal: SmartWeaveGlobal) {}
get height() {
if (!this.smartWeaveGlobal._activeTx) {
throw new Error('No current Tx');
}
return this.smartWeaveGlobal._activeTx.block.height;
}
get indep_hash() {
if (!this.smartWeaveGlobal._activeTx) {
throw new Error('No current Tx');
}
return this.smartWeaveGlobal._activeTx.block.id;
}
get timestamp() {
if (!this.smartWeaveGlobal._activeTx) {
throw new Error('No current tx');
}
return this.smartWeaveGlobal._activeTx.block.timestamp;
}
}
export class SWVrf {
constructor(private readonly smartWeaveGlobal: SmartWeaveGlobal) {}
get data(): VrfData {
return this.smartWeaveGlobal._activeTx.vrf;
}
// returns the original generated random number as a BigInt string;
get value(): string {
return this.smartWeaveGlobal._activeTx.vrf.bigint;
}
// returns a random value in a range from 1 to maxValue
randomInt(maxValue: number): number {
if (!Number.isInteger(maxValue)) {
throw new Error('Integer max value required for random integer generation');
}
const result = (BigInt(this.smartWeaveGlobal._activeTx.vrf.bigint) % BigInt(maxValue)) + BigInt(1);
if (result > Number.MAX_SAFE_INTEGER || result < Number.MIN_SAFE_INTEGER) {
throw new Error('Random int cannot be cast to number');
}
return Number(result);
}
}
export class KV {
constructor(
private readonly _storage: SortKeyCache<any> | null,
private readonly _interactionState: InteractionState,
private readonly _transaction: SWTransaction,
private readonly _contractTxId: string
) {}
async put(key: string, value: any): Promise<void> {
this.checkStorageAvailable();
await this._storage.put(new CacheKey(key, this._transaction.sortKey), value);
}
async get(key: string): Promise<unknown | null> {
this.checkStorageAvailable();
const sortKey = this._transaction.sortKey;
// then we're checking if the values exists in the interactionState
const interactionStateValue = await this._interactionState.getKV(
this._contractTxId,
new CacheKey(key, this._transaction.sortKey)
);
if (interactionStateValue != null) {
return interactionStateValue;
}
const result = await this._storage.getLessOrEqual(key, this._transaction.sortKey);
return result?.cachedValue ?? null;
}
async del(key: string): Promise<void> {
this.checkStorageAvailable();
const sortKey = this._transaction.sortKey;
// then we're checking if the values exists in the interactionState
const interactionStateValue = await this._interactionState.delKV(
this._contractTxId,
new CacheKey(key, this._transaction.sortKey)
);
if (interactionStateValue != null) {
return interactionStateValue;
}
await this._storage.del(new CacheKey(key, this._transaction.sortKey));
}
async keys(options?: SortKeyCacheRangeOptions): Promise<string[]> {
const sortKey = this._transaction.sortKey;
return await this._storage.keys(sortKey, options);
}
async kvMap<V>(options?: SortKeyCacheRangeOptions): Promise<Map<string, V>> {
const sortKey = this._transaction.sortKey;
return this._storage.kvMap(sortKey, options);
}
async begin() {
if (this._storage) {
return this._storage.begin();
}
}
async commit(): Promise<void> {
if (this._storage) {
if (this._transaction.dryRun) {
await this._storage.rollback();
} else {
await this._storage.commit();
}
}
}
async rollback(): Promise<void> {
if (this._storage) {
await this._storage.rollback();
}
}
open(): Promise<void> {
if (this._storage) {
return this._storage.open();
}
}
close(): Promise<void> {
if (this._storage) {
return this._storage.close();
}
}
private checkStorageAvailable() {
if (!this._storage) {
throw new Error('KV Storage not available');
}
}
}