|
| 1 | +// # What is this file? |
| 2 | +// This file is a "hack" to allow global variables in subgraphs and |
| 3 | +// on this library (`graph-ts`). |
| 4 | +// |
| 5 | +// # Why is it needed? |
| 6 | +// It's necessary because of one of the features of the AssemblyScript |
| 7 | +// compiler we use, the stub runtime. |
| 8 | +// |
| 9 | +// The problem happens because we call the stub runtime allocation |
| 10 | +// (`__alloc`) directly on Rust side (`graph-node`), and that doesn't |
| 11 | +// trigger some AssemblyScript aspects of the code. |
| 12 | +// |
| 13 | +// If you take a look at the stub runtime's code, you'll see that the |
| 14 | +// `__alloc` function uses a variable named `offset` tagged as `lazy`. |
| 15 | +// Like said above, since we call it on Rust side, this variable is not |
| 16 | +// "triggered" to be used, then it's declared below the `__alloc` call |
| 17 | +// in the compiled WASM code. |
| 18 | +// |
| 19 | +// That makes the `graph-node` WASM runtime break because of this out |
| 20 | +// of order variable usage. |
| 21 | +// |
| 22 | +// # How does this fix the issue? |
| 23 | +// The way this workaround works is by calling the `__alloc` function |
| 24 | +// before everything in the AssemblyScript side. This makes the `offset` |
| 25 | +// `lazy` variable be eagerly evaluated when the mappings are compiled |
| 26 | +// (since they always import `graph-ts`). |
| 27 | +// |
| 28 | +// So when we're on Rust side calling `__alloc` it will be fine, because |
| 29 | +// the `offset` is declared before call (order fixed because of this file). |
| 30 | +// |
| 31 | +// The 0 argument to the function call is just because we need no memory |
| 32 | +// to be allocated. |
| 33 | +// |
| 34 | +// # IMPORTANT |
| 35 | +// This should be imported in EVERY file which uses external namespaces (`graph-node` host-exports code), |
| 36 | +// just to make sure no one imports a file directly and gets an error on global variables. |
| 37 | +// |
| 38 | +// # Reference |
| 39 | +// - Runtimes in AS: https://www.assemblyscript.org/garbage-collection.html#runtime-variants |
| 40 | +// - `offset` variable in question: https://github.com/AssemblyScript/assemblyscript/blob/f4091b8f3b6b029d30cd917cf84d97421faadeeb/std/assembly/rt/stub.ts#L9 |
| 41 | +// @ts-expect-error We do not want to expose __alloc, hence why we just ignore the error |
| 42 | +__alloc(0); |
0 commit comments