envio 3.15.0-subgraph → 3.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (186) hide show
  1. package/README.md +40 -34
  2. package/evm.schema.json +3 -3
  3. package/fuel.schema.json +2 -2
  4. package/index.d.ts +3 -3
  5. package/licenses/README.md +1 -1
  6. package/package.json +9 -10
  7. package/src/Batch.res.mjs +5 -5
  8. package/src/BatchProcessing.res +1 -0
  9. package/src/BatchProcessing.res.mjs +1 -0
  10. package/src/Bin.res +0 -7
  11. package/src/Bin.res.mjs +0 -8
  12. package/src/ChainFetching.res +17 -456
  13. package/src/ChainFetching.res.mjs +33 -404
  14. package/src/ChainState.res +48 -83
  15. package/src/ChainState.res.mjs +83 -115
  16. package/src/ChainState.resi +0 -26
  17. package/src/Clock.res +57 -0
  18. package/src/Clock.res.mjs +72 -0
  19. package/src/Config.res +7 -16
  20. package/src/Config.res.mjs +4 -11
  21. package/src/ContractRegisterContext.res +6 -3
  22. package/src/ContractRegisterContext.res.mjs +2 -4
  23. package/src/Core.res +5 -136
  24. package/src/Core.res.mjs +1 -90
  25. package/src/CrossChainState.res +2 -8
  26. package/src/CrossChainState.res.mjs +3 -3
  27. package/src/Ecosystem.res +4 -7
  28. package/src/Ecosystem.res.mjs +8 -8
  29. package/src/EffectState.res +10 -2
  30. package/src/EffectState.res.mjs +8 -4
  31. package/src/EffectState.resi +3 -1
  32. package/src/EntityId.res +2 -7
  33. package/src/EntityId.res.mjs +1 -8
  34. package/src/EntityTables.res +4 -1
  35. package/src/EntityTables.res.mjs +1 -1
  36. package/src/Env.res +0 -16
  37. package/src/Env.res.mjs +0 -11
  38. package/src/EventProcessing.res +1 -38
  39. package/src/EventProcessing.res.mjs +1 -28
  40. package/src/FetchState.res +160 -319
  41. package/src/FetchState.res.mjs +182 -292
  42. package/src/FinalizeBackfill.res +2 -4
  43. package/src/FinalizeBackfill.res.mjs +3 -4
  44. package/src/HandlerLoader.res +15 -39
  45. package/src/HandlerLoader.res.mjs +8 -27
  46. package/src/HandlerRegister.res +0 -4
  47. package/src/HandlerRegister.res.mjs +2 -5
  48. package/src/HandlerRegister.resi +0 -2
  49. package/src/InMemoryTable.res +17 -16
  50. package/src/InMemoryTable.res.mjs +14 -15
  51. package/src/IndexerState.res +28 -4
  52. package/src/IndexerState.res.mjs +19 -6
  53. package/src/IndexerState.resi +4 -0
  54. package/src/Internal.res +0 -110
  55. package/src/Internal.res.mjs +1 -115
  56. package/src/LoadLayer.res +21 -47
  57. package/src/LoadLayer.res.mjs +47 -72
  58. package/src/LoadLayer.resi +0 -26
  59. package/src/Main.res +1 -14
  60. package/src/Main.res.mjs +3 -4
  61. package/src/Persistence.res +3 -23
  62. package/src/Persistence.res.mjs +3 -3
  63. package/src/Rollback.res +0 -1
  64. package/src/Rollback.res.mjs +1 -1
  65. package/src/RunScope.res +0 -3
  66. package/src/SafeCheckpointTracking.res +4 -4
  67. package/src/SafeCheckpointTracking.res.mjs +1 -1
  68. package/src/SimulateItems.res +26 -42
  69. package/src/SimulateItems.res.mjs +16 -40
  70. package/src/StagedRows.res +106 -0
  71. package/src/StagedRows.res.mjs +102 -0
  72. package/src/Staging.res +32 -14
  73. package/src/Staging.res.mjs +17 -20
  74. package/src/Storage.res +277 -998
  75. package/src/Storage.res.mjs +216 -731
  76. package/src/Supervisor.res +75 -56
  77. package/src/Supervisor.res.mjs +55 -26
  78. package/src/TestIndexer.res +22 -27
  79. package/src/TestIndexer.res.mjs +20 -17
  80. package/src/Throttler.res +15 -8
  81. package/src/Throttler.res.mjs +9 -6
  82. package/src/Throttler.resi +1 -1
  83. package/src/UserContext.res +46 -410
  84. package/src/UserContext.res.mjs +30 -318
  85. package/src/Utils.res +0 -23
  86. package/src/Utils.res.mjs +1 -17
  87. package/src/Writing.res +0 -1
  88. package/src/Writing.res.mjs +1 -1
  89. package/src/bindings/ClickHouse.res +0 -322
  90. package/src/bindings/ClickHouse.res.mjs +0 -338
  91. package/src/bindings/StorageClient.res +107 -175
  92. package/src/bindings/StorageClient.res.mjs +19 -8
  93. package/src/bindings/Vitest.res +0 -26
  94. package/src/bindings/Vitest.res.mjs +0 -3
  95. package/src/db/Table.res +24 -150
  96. package/src/db/Table.res.mjs +38 -272
  97. package/src/sources/AddressSet.res +0 -2
  98. package/src/sources/AddressStore.res +0 -3
  99. package/src/sources/ChainSources.res +2 -0
  100. package/src/sources/ChainSources.res.mjs +2 -2
  101. package/src/sources/EvmChain.res +4 -7
  102. package/src/sources/EvmChain.res.mjs +5 -4
  103. package/src/sources/EvmHyperSyncSource.res +2 -2
  104. package/src/sources/EvmHyperSyncSource.res.mjs +1 -1
  105. package/src/sources/EvmRpcClient.res +13 -3
  106. package/src/sources/EvmRpcClient.res.mjs +4 -3
  107. package/src/sources/EvmRpcWs.res +4 -3
  108. package/src/sources/EvmRpcWs.res.mjs +2 -2
  109. package/src/sources/HeightFeed.res +31 -10
  110. package/src/sources/HeightFeed.res.mjs +10 -6
  111. package/src/sources/HeightStream.res +32 -17
  112. package/src/sources/HeightStream.res.mjs +10 -10
  113. package/src/sources/HyperSync.res +1 -2
  114. package/src/sources/HyperSync.res.mjs +1 -2
  115. package/src/sources/HyperSyncSSE.res +4 -6
  116. package/src/sources/HyperSyncSSE.res.mjs +2 -2
  117. package/src/sources/RpcSource.res +10 -1
  118. package/src/sources/RpcSource.res.mjs +4 -3
  119. package/src/sources/Source.res +3 -0
  120. package/src/sources/SourceManager.res +85 -104
  121. package/src/sources/SourceManager.res.mjs +18 -37
  122. package/src/sources/SourceManager.resi +3 -5
  123. package/src/sources/StartBlockResolver.res +1 -0
  124. package/src/sources/StartBlockResolver.res.mjs +4 -3
  125. package/src/sources/SvmHyperSyncSource.res +2 -2
  126. package/src/sources/SvmHyperSyncSource.res.mjs +1 -1
  127. package/svm.schema.json +3 -3
  128. package/src/EffectCacheLookup.res +0 -98
  129. package/src/EffectCacheLookup.res.mjs +0 -116
  130. package/src/PgWriting.res +0 -36
  131. package/src/PgWriting.res.mjs +0 -34
  132. package/src/PreloadLookahead.res +0 -184
  133. package/src/PreloadLookahead.res.mjs +0 -197
  134. package/src/SubgraphLog.res +0 -19
  135. package/src/SubgraphLog.res.mjs +0 -26
  136. package/src/SyncWrites.res +0 -101
  137. package/src/SyncWrites.res.mjs +0 -98
  138. package/src/db/IndexDefinition.res +0 -47
  139. package/src/db/IndexDefinition.res.mjs +0 -60
  140. package/src/sources/CallSource.res +0 -274
  141. package/src/sources/CallSource.res.mjs +0 -196
  142. package/src/subgraph/abi-types.ts +0 -84
  143. package/src/subgraph/aggregations.ts +0 -745
  144. package/src/subgraph/as-package.ts +0 -143
  145. package/src/subgraph/assemblyscript-regex.ts +0 -67
  146. package/src/subgraph/assemblyscript.ts +0 -731
  147. package/src/subgraph/blocks.ts +0 -398
  148. package/src/subgraph/calls-source.ts +0 -702
  149. package/src/subgraph/calls.ts +0 -258
  150. package/src/subgraph/conformance.ts +0 -106
  151. package/src/subgraph/errors.ts +0 -85
  152. package/src/subgraph/graft.ts +0 -73
  153. package/src/subgraph/graph-cli-worker.mjs +0 -35
  154. package/src/subgraph/graph-cli.ts +0 -900
  155. package/src/subgraph/graph-node-decimal.ts +0 -199
  156. package/src/subgraph/graph-ts-enums.ts +0 -28
  157. package/src/subgraph/graph-ts-types/VERSION +0 -2
  158. package/src/subgraph/graph-ts-types/chain/arweave.d.ts +0 -70
  159. package/src/subgraph/graph-ts-types/chain/cosmos.d.ts +0 -327
  160. package/src/subgraph/graph-ts-types/chain/ethereum.d.ts +0 -233
  161. package/src/subgraph/graph-ts-types/chain/near.d.ts +0 -253
  162. package/src/subgraph/graph-ts-types/chain/starknet.d.ts +0 -32
  163. package/src/subgraph/graph-ts-types/common/collections.d.ts +0 -136
  164. package/src/subgraph/graph-ts-types/common/conversion.d.ts +0 -11
  165. package/src/subgraph/graph-ts-types/common/datasource.d.ts +0 -30
  166. package/src/subgraph/graph-ts-types/common/eager-offset.d.ts +0 -0
  167. package/src/subgraph/graph-ts-types/common/json.d.ts +0 -17
  168. package/src/subgraph/graph-ts-types/common/numbers.d.ts +0 -120
  169. package/src/subgraph/graph-ts-types/common/value.d.ts +0 -120
  170. package/src/subgraph/graph-ts-types/common/yaml.d.ts +0 -90
  171. package/src/subgraph/graph-ts-types/global/global.d.ts +0 -194
  172. package/src/subgraph/graph-ts-types/helper-functions.d.ts +0 -22
  173. package/src/subgraph/graph-ts-types/index.d.ts +0 -102
  174. package/src/subgraph/graph-ts.ts +0 -4280
  175. package/src/subgraph/hosts.ts +0 -554
  176. package/src/subgraph/log.ts +0 -28
  177. package/src/subgraph/receipts.ts +0 -184
  178. package/src/subgraph/register-slots.ts +0 -93
  179. package/src/subgraph/rollup.ts +0 -109
  180. package/src/subgraph/rpc.ts +0 -337
  181. package/src/subgraph/runtime.ts +0 -2060
  182. package/src/subgraph/scope.ts +0 -177
  183. package/src/subgraph/stats.ts +0 -42
  184. package/src/subgraph/template-instances.ts +0 -66
  185. package/src/subgraph/toolchain.ts +0 -327
  186. package/src/subgraph/transient.ts +0 -176
@@ -1,731 +0,0 @@
1
- /**
2
- * The runtime half of `packages/cli/src/subgraph/assemblyscript.rs`, which
3
- * rewrites every arithmetic and comparison operator in a mapping into a call
4
- * on `OPERATORS_HELPER`, every `changetype<Foo>(x)` into one to `RETAG_HELPER`,
5
- * and exports each handler's event class as `EVENT_CLASSES_EXPORT`. The names
6
- * are shared with that file.
7
- */
8
-
9
- import { BigDecimal, BigInt as GraphBigInt } from "./graph-ts.ts";
10
-
11
- export const OPERATORS_HELPER = "__envio_op";
12
- export const RETAG_HELPER = "__envio_retag";
13
- export const RETAG_EACH_HELPER = "__envio_retag_each";
14
- export const EVENT_CLASSES_EXPORT = "__envio_event_classes";
15
- /** Reruns a project module's top-level code for a new trigger. */
16
- export const MODULE_INIT = "__envio_init";
17
- export const AS_MAP = "__envio_Map";
18
- export const AS_SET = "__envio_Set";
19
-
20
- /**
21
- * AssemblyScript divides two integers as integers; this truncates only when
22
- * both operands really are integers and otherwise divides as before — an `f64`
23
- * divides as a float in AssemblyScript too.
24
- */
25
- export function integerDivision(a: unknown, b: unknown): unknown {
26
- const left = typeof a === "object" && a !== null ? (a as any).valueOf() : a;
27
- const right = typeof b === "object" && b !== null ? (b as any).valueOf() : b;
28
-
29
- const integral = (v: unknown) =>
30
- typeof v === "bigint" || (typeof v === "number" && Number.isInteger(v));
31
- if (integral(left) && integral(right)) {
32
- // An i64 on either side makes it an i64 division (the other side is a
33
- // literal or a widened integer); anything narrower is an i32 in
34
- // AssemblyScript and must come back as a number, or the bigint spreads
35
- // through every arithmetic that follows.
36
- if (typeof left === "bigint" || typeof right === "bigint") {
37
- return BigInt(left as bigint | number) / BigInt(right as bigint | number);
38
- }
39
- return Math.trunc(Number(left) / Number(right));
40
- }
41
- return (left as number) / (right as number);
42
- }
43
-
44
- /**
45
- * An i64 with an integer on the other side is i64 arithmetic in
46
- * AssemblyScript — `timestamp.toI64() * 1000` — where JavaScript refuses to
47
- * mix a bigint with a number.
48
- */
49
- const widened =
50
- (op: (a: any, b: any) => unknown) =>
51
- (a: unknown, b: unknown): unknown => {
52
- if (typeof a === "bigint" && typeof b === "number" && Number.isInteger(b)) return op(a, BigInt(b));
53
- if (typeof b === "bigint" && typeof a === "number" && Number.isInteger(a)) return op(BigInt(a), b);
54
- return op(a, b);
55
- };
56
-
57
- /** The graph-ts operator overload `value` declares under `method`, if any. */
58
- function overload(value: unknown, method: string): Function | undefined {
59
- if (!isObject(value)) return undefined;
60
- const fn = (value as Record<string, unknown>)[method];
61
- return typeof fn === "function" ? fn : undefined;
62
- }
63
-
64
- function isObject(value: unknown): boolean {
65
- return value !== null && typeof value === "object";
66
- }
67
-
68
- // Both operands are objects wherever AssemblyScript picks the overload — it
69
- // doesn't compile `BigInt < i32` — so a primitive on either side is left to
70
- // JavaScript, which reads the object through `valueOf`.
71
- const binary =
72
- (method: string, fallback: (a: any, b: any) => unknown) =>
73
- (a: unknown, b: unknown): unknown => {
74
- const declared = isObject(b) ? overload(a, method) : undefined;
75
- return declared ? declared.call(a, b) : fallback(a, b);
76
- };
77
-
78
- /**
79
- * `let result: JsonResult; result.error = "none"; return result;`: asc gives
80
- * the local the null pointer, and the field writes land at that address, so
81
- * every such local reads back what any of them wrote (one per class here, as
82
- * the code that relies on it writes the fields it reads). It is still null to
83
- * a comparison. graph-node's module memory is fresh in every trigger, and so
84
- * are these.
85
- */
86
- let nullObjects = new Map<Function, object>();
87
- let liveNullObjects = new WeakSet<object>();
88
- export function resetNullObjects(): void {
89
- if (nullObjects.size === 0) return;
90
- nullObjects = new Map();
91
- liveNullObjects = new WeakSet();
92
- }
93
- const nullObject = (Class: Function): object => {
94
- let object = nullObjects.get(Class);
95
- if (!object) {
96
- object = Object.create(Class.prototype) as object;
97
- nullObjects.set(Class, object);
98
- liveNullObjects.add(object);
99
- }
100
- return object;
101
- };
102
- const asNull = (value: unknown): unknown =>
103
- nullObjects.size > 0 && isObject(value) && liveNullObjects.has(value as object) ? null : value;
104
-
105
- // Against null AssemblyScript compares the reference, overload or not.
106
- const equals = (a: unknown, b: unknown): boolean => {
107
- a = asNull(a);
108
- b = asNull(b);
109
- const declared = isObject(b) ? overload(a, "equals") : undefined;
110
- return declared ? (declared.call(a, b) as boolean) : a == b;
111
- };
112
-
113
- /**
114
- * A bit operation where either side is an i64 — a bigint here — is a 64-bit
115
- * one in AssemblyScript, the i32 side widened; JavaScript refuses to mix the
116
- * two. Two numbers keep JavaScript's int32 operation, which is an i32's.
117
- */
118
- const bits64 =
119
- (op: (a: bigint, b: bigint) => bigint, numbers: (a: number, b: number) => number) =>
120
- (a: unknown, b: unknown): unknown => {
121
- if (typeof a !== "bigint" && typeof b !== "bigint") return numbers(a as number, b as number);
122
- return op(BigInt(a as bigint | number), BigInt(b as bigint | number));
123
- };
124
- // A u64 stays unsigned through a left shift, an i64 keeps its sign.
125
- const wrap64 = (from: bigint, value: bigint) => (from < 0n ? BigInt.asIntN(64, value) : BigInt.asUintN(64, value));
126
-
127
- /**
128
- * AssemblyScript's `===`, which no class can overload: references are the same
129
- * object, numbers the same value once converted to a common type — an i64 the
130
- * shim holds as a bigint equals the number it was compared with, and a bool is
131
- * 0 or 1. Null is one value however the JavaScript side came to read it: a
132
- * class field AssemblyScript zero-initializes is `undefined` here.
133
- */
134
- const same = (a: unknown, b: unknown): boolean => {
135
- a = asNull(a);
136
- b = asNull(b);
137
- if (a === b) return true;
138
- if (a == null || b == null) return a == null && b == null;
139
- const numeric = (v: unknown) => typeof v === "number" || typeof v === "bigint" || typeof v === "boolean";
140
- if (numeric(a) && numeric(b) && typeof a !== typeof b) {
141
- const n = (v: unknown) => (typeof v === "boolean" ? (v ? 1 : 0) : v);
142
- return n(a) == n(b);
143
- }
144
- return false;
145
- };
146
-
147
- /**
148
- * `===` where one side is a string the host has just allocated (the transform
149
- * marks it): no other string is that allocation, whatever it reads.
150
- */
151
- const sameFresh = (a: unknown, b: unknown): boolean =>
152
- typeof a === "string" && typeof b === "string" ? false : same(a, b);
153
-
154
- /**
155
- * `changetype<usize>(ref)`: the reference's address. Null is 0 and each object
156
- * keeps one nonzero address, which is all a mapping can observe of one — it
157
- * tests it against 0, or two of them against each other. A string here is a
158
- * value, so equal strings share an address; an integer is itself.
159
- */
160
- const objectAddresses = new WeakMap<object, number>();
161
- const stringAddresses = new Map<string, number>();
162
- let lastAddress = 0;
163
- const nextAddress = () => (lastAddress += 16);
164
- /**
165
- * An AssemblyScript pointer into a buffer — `x.dataStart`,
166
- * `changetype<usize>(x.buffer)` — for `load`, `store` and `memory.copy`, and
167
- * pointer arithmetic on it. As a number it is a stable address of its own.
168
- */
169
- export class Pointer {
170
- constructor(
171
- readonly buffer: ArrayBufferLike,
172
- readonly offset: number,
173
- ) {}
174
- at(delta: number): Pointer {
175
- return new Pointer(this.buffer, this.offset + delta);
176
- }
177
- valueOf(): number {
178
- return objectAddress(this.buffer as object) + this.offset;
179
- }
180
- }
181
-
182
- const isBuffer = (value: unknown): value is ArrayBufferLike =>
183
- value instanceof ArrayBuffer || (typeof SharedArrayBuffer !== "undefined" && value instanceof SharedArrayBuffer);
184
-
185
- function pointer(value: unknown, what: string): Pointer {
186
- if (value instanceof Pointer) return value;
187
- throw new Error(
188
- `Envio Subgraph can't ${what} at a raw memory address (${String(value)}): only a pointer into a buffer, ` +
189
- "from x.dataStart or changetype<usize>(x.buffer), addresses memory here.",
190
- );
191
- }
192
-
193
- type Width = { size: number; get: (view: DataView, at: number) => unknown; set: (view: DataView, at: number, value: unknown) => void };
194
- const number = (value: unknown) => Number(typeof value === "boolean" ? Number(value) : value);
195
- const big = (value: unknown) => (typeof value === "bigint" ? value : BigInt(Math.trunc(number(value))));
196
- const WIDTHS: Record<string, Width> = {
197
- i8: { size: 1, get: (v, at) => v.getInt8(at), set: (v, at, x) => v.setInt8(at, number(x)) },
198
- u8: { size: 1, get: (v, at) => v.getUint8(at), set: (v, at, x) => v.setUint8(at, number(x)) },
199
- bool: { size: 1, get: (v, at) => v.getUint8(at) !== 0, set: (v, at, x) => v.setUint8(at, number(x) ? 1 : 0) },
200
- i16: { size: 2, get: (v, at) => v.getInt16(at, true), set: (v, at, x) => v.setInt16(at, number(x), true) },
201
- u16: { size: 2, get: (v, at) => v.getUint16(at, true), set: (v, at, x) => v.setUint16(at, number(x), true) },
202
- i32: { size: 4, get: (v, at) => v.getInt32(at, true), set: (v, at, x) => v.setInt32(at, number(x), true) },
203
- u32: { size: 4, get: (v, at) => v.getUint32(at, true), set: (v, at, x) => v.setUint32(at, number(x), true) },
204
- i64: { size: 8, get: (v, at) => v.getBigInt64(at, true), set: (v, at, x) => v.setBigInt64(at, BigInt.asIntN(64, big(x)), true) },
205
- u64: { size: 8, get: (v, at) => v.getBigUint64(at, true), set: (v, at, x) => v.setBigUint64(at, BigInt.asUintN(64, big(x)), true) },
206
- f32: { size: 4, get: (v, at) => v.getFloat32(at, true), set: (v, at, x) => v.setFloat32(at, number(x), true) },
207
- f64: { size: 8, get: (v, at) => v.getFloat64(at, true), set: (v, at, x) => v.setFloat64(at, number(x), true) },
208
- };
209
- WIDTHS.isize = WIDTHS.i32;
210
- WIDTHS.usize = WIDTHS.u32;
211
-
212
- function width(type: string): Width {
213
- const found = WIDTHS[type];
214
- if (!found) throw new Error(`Envio Subgraph can't load or store a ${type} in memory: only integer, float and bool values.`);
215
- return found;
216
- }
217
-
218
- /** AssemblyScript's `memory` builtin, over the buffers pointers address. */
219
- export const memory = {
220
- copy(destination: unknown, source: unknown, length: unknown): void {
221
- const to = pointer(destination, "copy memory");
222
- const from = pointer(source, "copy memory");
223
- const count = number(length);
224
- // TypedArray#set copies an overlapping range as memmove does.
225
- new Uint8Array(to.buffer, to.offset, count).set(new Uint8Array(from.buffer, from.offset, count));
226
- },
227
- fill(destination: unknown, value: unknown, length: unknown): void {
228
- const to = pointer(destination, "fill memory");
229
- new Uint8Array(to.buffer, to.offset, number(length)).fill(number(value));
230
- },
231
- };
232
-
233
- const bytesAt = (buffer: unknown, what: string): Uint8Array => {
234
- if (isBuffer(buffer)) return new Uint8Array(buffer);
235
- if (ArrayBuffer.isView(buffer)) return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
236
- throw new Error(`Envio Subgraph: String.${what} takes an ArrayBuffer, not ${String(buffer)}.`);
237
- };
238
-
239
- /**
240
- * AssemblyScript's UTF-8 decoder (std/assembly/string.ts, asc 0.19.10): it
241
- * validates nothing and replaces nothing, takes a lead byte's payload bits as
242
- * they are, and stops at a sequence the input cuts short.
243
- */
244
- function decodeUtf8(bytes: Uint8Array, nullTerminated: unknown): string {
245
- const units: number[] = [];
246
- const end = bytes.length;
247
- let at = 0;
248
- while (at < end) {
249
- let u0 = bytes[at++]!;
250
- if (!(u0 & 128)) {
251
- if (nullTerminated && !u0) break;
252
- units.push(u0);
253
- continue;
254
- }
255
- if (at === end) break;
256
- const u1 = bytes[at++]! & 63;
257
- if ((u0 & 224) === 192) {
258
- units.push((((u0 & 31) << 6) | u1) & 0xffff);
259
- continue;
260
- }
261
- if (at === end) break;
262
- const u2 = bytes[at++]! & 63;
263
- if ((u0 & 240) === 224) {
264
- u0 = ((u0 & 15) << 12) | (u1 << 6) | u2;
265
- } else {
266
- if (at === end) break;
267
- u0 = ((u0 & 7) << 18) | (u1 << 12) | (u2 << 6) | (bytes[at++]! & 63);
268
- }
269
- if (u0 < 0x10000) {
270
- units.push(u0);
271
- } else {
272
- u0 -= 0x10000;
273
- units.push(((u0 >> 10) | 0xd800) & 0xffff, (u0 & 0x03ff) | 0xdc00);
274
- }
275
- }
276
- let text = "";
277
- for (let from = 0; from < units.length; from += 8192) text += String.fromCharCode(...units.slice(from, from + 8192));
278
- return text;
279
- }
280
-
281
- /** AssemblyScript's UTF-8 encoder in its default WTF-8 mode: a lone surrogate is three bytes. */
282
- function encodeUtf8(text: string, nullTerminated: unknown): ArrayBuffer {
283
- const bytes: number[] = [];
284
- for (let at = 0; at < text.length; at++) {
285
- let c1 = text.charCodeAt(at);
286
- if (c1 < 128) {
287
- bytes.push(c1);
288
- } else if (c1 < 2048) {
289
- bytes.push((c1 >> 6) | 192, (c1 & 63) | 128);
290
- } else {
291
- const c2 = at + 1 < text.length ? text.charCodeAt(at + 1) : 0;
292
- if ((c1 & 0xfc00) === 0xd800 && (c2 & 0xfc00) === 0xdc00) {
293
- c1 = (0x10000 + ((c1 & 0x03ff) << 10)) | (c2 & 0x03ff);
294
- bytes.push((c1 >> 18) | 240, ((c1 >> 12) & 63) | 128, ((c1 >> 6) & 63) | 128, (c1 & 63) | 128);
295
- at++;
296
- continue;
297
- }
298
- bytes.push((c1 >> 12) | 224, ((c1 >> 6) & 63) | 128, (c1 & 63) | 128);
299
- }
300
- }
301
- if (nullTerminated) bytes.push(0);
302
- return new Uint8Array(bytes).buffer;
303
- }
304
-
305
- /**
306
- * The `String.UTF8` and `String.UTF16` namespaces of AssemblyScript's String,
307
- * which JavaScript's lacks. A pointer from `x.dataStart` stands in for the
308
- * `usize` the unsafe variants take.
309
- */
310
- export const stringEncodings = {
311
- UTF8: {
312
- byteLength: (text: string, nullTerminated: unknown = false): number =>
313
- encodeUtf8(text, nullTerminated).byteLength,
314
- encode: (text: string, nullTerminated: unknown = false): ArrayBuffer => encodeUtf8(text, nullTerminated),
315
- decode: (buffer: unknown, nullTerminated: unknown = false): string =>
316
- decodeUtf8(bytesAt(buffer, "UTF8.decode"), nullTerminated),
317
- decodeUnsafe: (at: unknown, length: unknown, nullTerminated: unknown = false): string => {
318
- const p = pointer(at, "decode a string");
319
- return decodeUtf8(new Uint8Array(p.buffer, p.offset, number(length)), nullTerminated);
320
- },
321
- },
322
- UTF16: {
323
- byteLength: (text: string): number => text.length * 2,
324
- encode: (text: string): ArrayBuffer => {
325
- const view = new DataView(new ArrayBuffer(text.length * 2));
326
- for (let at = 0; at < text.length; at++) view.setUint16(at * 2, text.charCodeAt(at), true);
327
- return view.buffer;
328
- },
329
- decode: (buffer: unknown): string => {
330
- const bytes = bytesAt(buffer, "UTF16.decode");
331
- const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength & ~1);
332
- let text = "";
333
- for (let at = 0; at < view.byteLength; at += 2) text += String.fromCharCode(view.getUint16(at, true));
334
- return text;
335
- },
336
- },
337
- };
338
-
339
- /** The bit width of an integer builtin's operand: its type, or its value. */
340
- function bitsOf(type: string, value: unknown): 16 | 32 | 64 {
341
- if (type === "u16" || type === "i16") return 16;
342
- if (type === "u64" || type === "i64") return 64;
343
- if (type) return 32;
344
- return typeof value === "bigint" ? 64 : 32;
345
- }
346
- const signed = (type: string) => type.startsWith("i");
347
-
348
- const bswap = (value: unknown, type = ""): unknown => {
349
- const bits = bitsOf(type, value);
350
- if (bits === 64) {
351
- let rest = BigInt.asUintN(64, big(value));
352
- let out = 0n;
353
- for (let i = 0; i < 8; i++) {
354
- out = (out << 8n) | (rest & 0xffn);
355
- rest >>= 8n;
356
- }
357
- return signed(type) ? BigInt.asIntN(64, out) : out;
358
- }
359
- const v = number(value) >>> 0;
360
- if (bits === 16) {
361
- const swapped = ((v & 0xff) << 8) | ((v >>> 8) & 0xff);
362
- return signed(type) ? (swapped << 16) >> 16 : swapped;
363
- }
364
- const swapped = (((v & 0xff) << 24) | ((v & 0xff00) << 8) | ((v >>> 8) & 0xff00) | (v >>> 24)) >>> 0;
365
- return signed(type) ? swapped | 0 : swapped;
366
- };
367
-
368
- const rotate = (left: boolean) => (value: unknown, shift: unknown, type = ""): unknown => {
369
- const bits = bitsOf(type, value);
370
- if (bits === 64) {
371
- const v = BigInt.asUintN(64, big(value));
372
- const s = big(shift) & 63n;
373
- const out = BigInt.asUintN(64, left ? (v << s) | (v >> ((64n - s) & 63n)) : (v >> s) | (v << ((64n - s) & 63n)));
374
- return signed(type) ? BigInt.asIntN(64, out) : out;
375
- }
376
- const v = number(value) >>> 0;
377
- const s = number(shift) & 31;
378
- const out = (left ? (v << s) | (v >>> ((32 - s) & 31)) : (v >>> s) | (v << ((32 - s) & 31))) >>> 0;
379
- return signed(type) ? out | 0 : out;
380
- };
381
-
382
- const TYPED_ARRAYS: Record<string, new (length: number) => ArrayLike<number>> = {
383
- i8: Int8Array,
384
- u8: Uint8Array,
385
- i16: Int16Array,
386
- u16: Uint16Array,
387
- i32: Int32Array,
388
- u32: Uint32Array,
389
- f32: Float32Array,
390
- f64: Float64Array,
391
- };
392
-
393
- /** AssemblyScript's generic `min`/`max` builtins. */
394
- export const builtinMin = (a: any, b: any) => (b < a ? b : a);
395
- export const builtinMax = (a: any, b: any) => (b > a ? b : a);
396
-
397
- const address = (value: unknown): unknown => {
398
- value = asNull(value);
399
- if (value === null || value === undefined) return 0;
400
- if (isBuffer(value)) return new Pointer(value, 0);
401
- if (typeof value === "number" || typeof value === "bigint") return value;
402
- if (typeof value === "boolean") return value ? 1 : 0;
403
- if (typeof value === "string") {
404
- if (stringAddresses.size > 100_000) stringAddresses.clear();
405
- let at = stringAddresses.get(value);
406
- if (at === undefined) stringAddresses.set(value, (at = nextAddress()));
407
- return at;
408
- }
409
- return objectAddress(value as object);
410
- };
411
-
412
- function objectAddress(value: object): number {
413
- let at = objectAddresses.get(value);
414
- if (at === undefined) objectAddresses.set(value, (at = nextAddress()));
415
- return at;
416
- }
417
-
418
- /**
419
- * `x as i32` and its narrower kin. A number or bigint wraps to the width; a
420
- * boolean is 0 or 1; null is 0. Anything else is a reference, and an
421
- * AssemblyScript cast of one reads its address, which is garbage the mapping
422
- * never meant — revert-univ3 casts a call result — so it comes out as 0
423
- * rather than the NaN that `BigInt.fromI32` then refuses.
424
- */
425
- const wrapTo = (bits: number, signed: boolean) => (value: unknown): number => {
426
- let n: number;
427
- if (typeof value === "bigint") n = Number(BigInt.asIntN(32, value));
428
- else if (typeof value === "number") n = value;
429
- else if (typeof value === "boolean") n = value ? 1 : 0;
430
- else n = 0;
431
- if (!Number.isFinite(n)) return 0;
432
- const wrapped = (Math.trunc(n) | 0) as number;
433
- if (bits === 32) return signed ? wrapped : wrapped >>> 0;
434
- const mask = (1 << bits) - 1;
435
- const low = wrapped & mask;
436
- return signed && low >= 1 << (bits - 1) ? low - (1 << bits) : low;
437
- };
438
-
439
- /**
440
- * `x as i64` and `x as u64`: a bigint of that width. A number truncates toward
441
- * zero and an i32 sign-extends before the wrap, as `i64.extend_i32_s` and
442
- * `i64.trunc_f64_s` do; a reference, like `as i32`'s, is 0.
443
- */
444
- const wrapTo64 = (signed: boolean) => (value: unknown): bigint => {
445
- let n: bigint;
446
- if (typeof value === "bigint") n = value;
447
- else if (typeof value === "number") n = Number.isFinite(value) ? BigInt(Math.trunc(value)) : 0n;
448
- else if (typeof value === "boolean") n = value ? 1n : 0n;
449
- else n = 0n;
450
- return signed ? BigInt.asIntN(64, n) : BigInt.asUintN(64, n);
451
- };
452
-
453
- /**
454
- * AssemblyScript's `Array#indexOf`, `lastIndexOf` and `includes` compare each
455
- * element with `==`, so with graph-ts' overload: ENS's
456
- * `if (!coinTypes.includes(coinType))` finds a BigInt already there. A
457
- * string, a typed array, or a search for a primitive is JavaScript's own.
458
- */
459
- const search =
460
- (method: "indexOf" | "lastIndexOf" | "includes") =>
461
- (receiver: any, value: unknown, from?: number): unknown => {
462
- if (!Array.isArray(receiver) || !overload(value, "equals")) {
463
- return from === undefined ? receiver[method](value) : receiver[method](value, from);
464
- }
465
- const length = receiver.length;
466
- if (method === "lastIndexOf") {
467
- let index = from === undefined ? length - 1 : from < 0 ? length + from : Math.min(from, length - 1);
468
- for (; index >= 0; index--) if (equals(receiver[index], value)) return index;
469
- return -1;
470
- }
471
- let index = from === undefined ? 0 : from < 0 ? Math.max(length + from, 0) : from;
472
- for (; index < length; index++) if (equals(receiver[index], value)) return method === "includes" ? true : index;
473
- return method === "includes" ? false : -1;
474
- };
475
-
476
- /**
477
- * AssemblyScript's default comparator (std/assembly/util/sort.ts COMPARATOR):
478
- * numbers by value, strings by code unit, and another reference by `a > b`
479
- * and `a < b` — graph-ts' BigInt and BigDecimal overload them. A reference
480
- * without the overload compares by address, its allocation order; here it
481
- * keeps its place, the order the array was built in.
482
- */
483
- function defaultCompare(a: unknown, b: unknown): number {
484
- if (typeof a === "string" && typeof b === "string") return a < b ? -1 : a > b ? 1 : 0;
485
- const greater = isObject(b) ? overload(a, "gt") : undefined;
486
- const less = isObject(b) ? overload(a, "lt") : undefined;
487
- if (greater && less) return (greater.call(a, b) ? 1 : 0) - (less.call(a, b) ? 1 : 0);
488
- const numeric = (v: unknown) => typeof v === "number" || typeof v === "bigint" || typeof v === "boolean";
489
- if (numeric(a) && numeric(b)) return (a as number) > (b as number) ? 1 : (a as number) < (b as number) ? -1 : 0;
490
- return 0;
491
- }
492
-
493
- const sort = (receiver: any): unknown => (Array.isArray(receiver) ? receiver.sort(defaultCompare) : receiver.sort());
494
-
495
- /**
496
- * What a graph-ts method on a null receiver computes below apiVersion 0.0.5,
497
- * where the host reads the null pointer as an empty value: a zero. Which zero
498
- * follows the argument (`null.plus(decimal)` is a decimal's), and a bytes
499
- * receiver is empty.
500
- */
501
- const nullReceiver: Record<string, (...args: any[]) => unknown> = {};
502
- const zeroFor = (other: unknown): any =>
503
- other instanceof BigDecimal ? BigDecimal.zero() : GraphBigInt.zero();
504
- for (const method of [
505
- "plus",
506
- "minus",
507
- "times",
508
- "div",
509
- "mod",
510
- "pow",
511
- "bitOr",
512
- "bitAnd",
513
- "leftShift",
514
- "rightShift",
515
- "abs",
516
- "neg",
517
- "toString",
518
- "toI32",
519
- "toBigDecimal",
520
- "isZero",
521
- "lt",
522
- "le",
523
- "gt",
524
- "ge",
525
- ]) {
526
- nullReceiver[method] = (...args) => zeroFor(args[0])[method](...args);
527
- }
528
- nullReceiver.truncate = (...args) => BigDecimal.zero().truncate(args[0]);
529
- nullReceiver.toHex = nullReceiver.toHexString = () => "0x";
530
- nullReceiver.equals = (other) =>
531
- other === null || other === undefined
532
- ? true
533
- : other instanceof Uint8Array && !(other instanceof GraphBigInt)
534
- ? other.length === 0
535
- : zeroFor(other).equals(other);
536
- nullReceiver.notEqual = (other) => !nullReceiver.equals(other);
537
-
538
- /**
539
- * What a mapping can name on one of these besides a key: the class's own
540
- * members, and what Node and the runtime look up on any object.
541
- */
542
- const NOT_KEYS = new Set(["then", "toJSON", "constructor", "valueOf", "toString", "inspect"]);
543
-
544
- /**
545
- * A property access that stands for `[]` on AssemblyScript's Map or Set: the
546
- * key as the collection holds it, a number when its numeric spelling is one.
547
- */
548
- function keyOf(target: Map<unknown, unknown> | Set<unknown>, prop: string): unknown {
549
- if (target.has(prop)) return prop;
550
- const number = Number(prop);
551
- if (prop !== "" && String(number) === prop && (target.has(number) || firstKeyIsNumber(target))) return number;
552
- return prop;
553
- }
554
-
555
- function firstKeyIsNumber(target: Map<unknown, unknown> | Set<unknown>): boolean {
556
- for (const key of target.keys()) return typeof key === "number";
557
- return false;
558
- }
559
-
560
- /**
561
- * Serves `collection[key]` and `collection[key] = value` through the class's
562
- * `[]` operators; its own members, bound to it, through everything else.
563
- */
564
- function indexedBy<T extends Map<unknown, unknown> | Set<unknown>>(
565
- collection: T,
566
- read: (target: T, key: unknown) => unknown,
567
- write: (target: T, key: unknown, value: unknown) => void,
568
- ): T {
569
- const bound = new Map<PropertyKey, Function>();
570
- return new Proxy(collection, {
571
- get(target, prop) {
572
- if (typeof prop === "symbol" || prop in target || NOT_KEYS.has(prop)) {
573
- const value = Reflect.get(target, prop, target);
574
- if (typeof value !== "function") return value;
575
- let method = bound.get(prop);
576
- if (!method) bound.set(prop, (method = value.bind(target)));
577
- return method;
578
- }
579
- return read(target, keyOf(target, prop));
580
- },
581
- set(target, prop, value) {
582
- if (typeof prop === "symbol" || prop in target) return Reflect.set(target, prop, value, target);
583
- write(target, keyOf(target, prop), value);
584
- return true;
585
- },
586
- });
587
- }
588
-
589
- /**
590
- * AssemblyScript's `Map` (std/assembly/map.ts): `keys()` and `values()` are
591
- * arrays, `get` of a missing key throws, and `[]` reads and writes an entry.
592
- */
593
- export class AsMap<K, V> extends Map<K, V> {
594
- constructor() {
595
- super();
596
- return indexedBy(
597
- this,
598
- (target, key) => target.get(key as K),
599
- (target, key, value) => target.set(key as K, value as V),
600
- );
601
- }
602
- get(key: K): V {
603
- if (!super.has(key)) throw new Error("Key does not exist");
604
- return super.get(key) as V;
605
- }
606
- keys(): any {
607
- return Array.from(super.keys());
608
- }
609
- values(): any {
610
- return Array.from(super.values());
611
- }
612
- }
613
-
614
- /**
615
- * AssemblyScript's `Set` (std/assembly/set.ts): `values()` is an array, `[]`
616
- * reads `has`, and `set[key] = flag` adds or deletes.
617
- */
618
- export class AsSet<T> extends Set<T> {
619
- constructor() {
620
- super();
621
- return indexedBy(
622
- this,
623
- (target, key) => target.has(key as T),
624
- (target, key, value) => (value ? target.add(key as T) : target.delete(key as T)),
625
- );
626
- }
627
- values(): any {
628
- return Array.from(super.values());
629
- }
630
- }
631
-
632
- const add = binary("plus", widened((a, b) => a + b));
633
- const sub = binary("minus", widened((a, b) => a - b));
634
-
635
- /**
636
- * graph-ts overloads the arithmetic and comparison operators on `BigInt`,
637
- * `BigDecimal` and `ByteArray`, and AssemblyScript calls the overload: a
638
- * JavaScript operator would coerce them, or compare their identity — so
639
- * `address == ZERO_ADDRESS` would always be false.
640
- */
641
- export const operators = {
642
- recv: (receiver: any): any => receiver ?? nullReceiver,
643
- add: (a: unknown, b: unknown): unknown =>
644
- a instanceof Pointer ? a.at(number(b)) : b instanceof Pointer ? b.at(number(a)) : add(a, b),
645
- sub: (a: unknown, b: unknown): unknown =>
646
- a instanceof Pointer
647
- ? b instanceof Pointer
648
- ? a.offset - b.offset
649
- : a.at(-number(b))
650
- : sub(a, b),
651
- load: (type: string, at: unknown, offset: unknown = 0): unknown => {
652
- const p = pointer(at, `load a ${type}`);
653
- return width(type).get(new DataView(p.buffer), p.offset + number(offset));
654
- },
655
- store: (type: string, at: unknown, value: unknown, offset: unknown = 0): void => {
656
- const p = pointer(at, `store a ${type}`);
657
- width(type).set(new DataView(p.buffer), p.offset + number(offset), value);
658
- },
659
- static_array: (element: string, length: unknown): unknown => new TYPED_ARRAYS[element](number(length)),
660
- null_object: nullObject,
661
- // `reinterpret<T>(x)`: x's bits as a T of x's width, the other of the pair
662
- // (std/assembly/builtins.ts: f32 <-> i32/u32, f64 <-> i64/u64).
663
- reinterpret: (type: string, value: unknown): unknown => {
664
- const view = new DataView(new ArrayBuffer(8));
665
- const from = { f32: "i32", f64: "i64", i32: "f32", u32: "f32", i64: "f64", u64: "f64" }[type];
666
- if (!from) throw new Error(`Envio Subgraph can't reinterpret a value as a ${type}: only between floats and integers of one width.`);
667
- width(from).set(view, 0, value);
668
- return width(type).get(view, 0);
669
- },
670
- bswap,
671
- rotl: rotate(true),
672
- rotr: rotate(false),
673
- mul: binary("times", widened((a, b) => a * b)),
674
- div: binary("div", integerDivision),
675
- // A division the source types as a float's, whole numbers or not.
676
- fdiv: binary("div", (a, b) => number(a) / number(b)),
677
- rem: binary("mod", widened((a, b) => a % b)),
678
- // `10 ** decimals.toI64()` is an i64 power, and graph-ts' `BigInt ** u8` its
679
- // `pow`: JavaScript's `**` refuses to mix a bigint with a number.
680
- pow: (a: unknown, b: unknown): unknown => {
681
- const declared = isObject(a) ? overload(a, "pow") : undefined;
682
- if (declared) return declared.call(a, typeof b === "bigint" ? Number(b) : b);
683
- if (typeof a === "bigint" || typeof b === "bigint") return BigInt(a as bigint | number) ** BigInt(b as bigint | number);
684
- return (a as number) ** (b as number);
685
- },
686
- eq: equals,
687
- ne: (a: unknown, b: unknown) => !equals(a, b),
688
- same,
689
- same_fresh: sameFresh,
690
- address,
691
- lt: binary("lt", (a, b) => a < b),
692
- le: binary("le", (a, b) => a <= b),
693
- gt: binary("gt", (a, b) => a > b),
694
- ge: binary("ge", (a, b) => a >= b),
695
- band: bits64((a, b) => a & b, (a, b) => a & b),
696
- bor: bits64((a, b) => a | b, (a, b) => a | b),
697
- bxor: bits64((a, b) => a ^ b, (a, b) => a ^ b),
698
- shl: bits64((a, b) => wrap64(a, a << (b & 63n)), (a, b) => a << b),
699
- shr: bits64((a, b) => a >> (b & 63n), (a, b) => a >> b),
700
- ushr: bits64((a, b) => BigInt.asUintN(64, a) >> (b & 63n), (a, b) => a >>> b),
701
- // A u32's bit operations, which AssemblyScript keeps unsigned.
702
- shl_u32: (a: unknown, b: unknown) => (Number(a) << Number(b)) >>> 0,
703
- shr_u32: (a: unknown, b: unknown) => Number(a) >>> Number(b),
704
- or_u32: (a: unknown, b: unknown) => (Number(a) | Number(b)) >>> 0,
705
- and_u32: (a: unknown, b: unknown) => (Number(a) & Number(b)) >>> 0,
706
- xor_u32: (a: unknown, b: unknown) => (Number(a) ^ Number(b)) >>> 0,
707
- as_i8: wrapTo(8, true),
708
- as_u8: wrapTo(8, false),
709
- as_i16: wrapTo(16, true),
710
- as_u16: wrapTo(16, false),
711
- as_i32: wrapTo(32, true),
712
- as_u32: wrapTo(32, false),
713
- // AssemblyScript's dtoa writes what JavaScript does, but a whole number
714
- // with ".0" (JavaScript already writes -0 as "0").
715
- ftoa: (value: unknown): string => {
716
- const text = String(isObject(value) ? value : number(value));
717
- return /^-?\d+$/.test(text) ? `${text}.0` : text;
718
- },
719
- as_i64: wrapTo64(true),
720
- as_u64: wrapTo64(false),
721
- as_f64: (value: unknown): unknown => (isObject(value) ? value : number(value ?? 0)),
722
- as_f32: (value: unknown): unknown => (isObject(value) ? value : Math.fround(number(value ?? 0))),
723
- neg: (a: unknown) => {
724
- const declared = overload(a, "neg");
725
- return declared ? declared.call(a) : -(a as number);
726
- },
727
- sort,
728
- indexOf: search("indexOf"),
729
- lastIndexOf: search("lastIndexOf"),
730
- includes: search("includes"),
731
- };