forked from graphprotocol/graph-tooling
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscaffold.js
More file actions
364 lines (322 loc) · 10.6 KB
/
scaffold.js
File metadata and controls
364 lines (322 loc) · 10.6 KB
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
const fs = require('fs-extra')
const path = require('path')
const prettier = require('prettier')
const pkginfo = require('pkginfo')(module)
const { getSubgraphBasename } = require('./command-helpers/subgraph')
const { step } = require('./command-helpers/spinner')
const { ascTypeForEthereum, valueTypeForAsc } = require('./codegen/types')
// TODO: Use Protocol class to getABI
const ABI = require('./protocols/ethereum/abi')
const AbiCodeGenerator = require('./protocols/ethereum/codegen/abi')
const util = require('./codegen/util')
const abiEvents = abi =>
util.disambiguateNames({
values: abi.data.filter(item => item.get('type') === 'event'),
getName: event => event.get('name'),
setName: (event, name) => event.set('_alias', name),
})
const graphCliVersion = process.env.GRAPH_CLI_TESTS
// JSON.stringify should remove this key, we will install the local
// graph-cli for the tests using `npm link` instead of fetching from npm.
? undefined
// For scaffolding real subgraphs
: `${module.exports.version}`
// package.json
const generatePackageJson = ({ subgraphName, node }) =>
prettier.format(
JSON.stringify({
name: getSubgraphBasename(subgraphName),
license: 'UNLICENSED',
scripts: {
codegen: 'graph codegen',
build: 'graph build',
deploy:
`graph deploy ` +
`--node ${node} ` +
subgraphName,
'create-local': `graph create --node http://localhost:8020/ ${subgraphName}`,
'remove-local': `graph remove --node http://localhost:8020/ ${subgraphName}`,
'deploy-local':
`graph deploy ` +
`--node http://localhost:8020/ ` +
`--ipfs http://localhost:5001 ` +
subgraphName,
},
dependencies: {
'@graphprotocol/graph-cli': graphCliVersion,
'@graphprotocol/graph-ts': `0.23.1`,
},
}),
{ parser: 'json' },
)
// Subgraph manifest
const generateManifest = ({ abi, address, network, contractName }) =>
prettier.format(
`
specVersion: 0.0.1
schema:
file: ./schema.graphql
dataSources:
- kind: ethereum/contract
name: ${contractName}
network: ${network}
source:
address: '${address}'
abi: ${contractName}
mapping:
kind: ethereum/events
apiVersion: 0.0.5
language: wasm/assemblyscript
entities:
${abiEvents(abi)
.map(event => `- ${event.get('_alias')}`)
.join('\n ')}
abis:
- name: ${contractName}
file: ./abis/${contractName}.json
eventHandlers:
${abiEvents(abi)
.map(
event => `
- event: ${ABI.eventSignature(event)}
handler: handle${event.get('_alias')}`,
)
.join('')}
file: ./src/mapping.ts
`,
{ parser: 'yaml' },
)
// Schema
const ethereumTypeToGraphQL = name => {
let ascType = ascTypeForEthereum(name)
return valueTypeForAsc(ascType)
}
const generateField = ({ name, type }) =>
`${name}: ${ethereumTypeToGraphQL(type)}! # ${type}`
const generateEventFields = ({ index, input }) =>
input.type == 'tuple'
? util
.unrollTuple({ value: input, path: [input.name || `param${index}`], index })
.map(({ path, type }) => generateField({ name: path.join('_'), type }))
: [generateField({ name: input.name || `param${index}`, type: input.type })]
const generateEventType = event => `type ${event._alias} @entity {
id: ID!
${event.inputs
.reduce(
(acc, input, index) => acc.concat(generateEventFields({ input, index })),
[],
)
.join('\n')}
}`
const generateExampleEntityType = events => {
if (events.length > 0) {
return `type ExampleEntity @entity {
id: ID!
count: BigInt!
${events[0].inputs
.reduce((acc, input, index) => acc.concat(generateEventFields({ input, index })), [])
.slice(0, 2)
.join('\n')}
}`
} else {
return `type ExampleEntity @entity {
id: ID!
block: Bytes!
transaction: Bytes!
}`
}
}
const generateSchema = ({ abi, indexEvents }) => {
let events = abiEvents(abi).toJS()
return prettier.format(
indexEvents
? events.map(generateEventType).join('\n\n')
: generateExampleEntityType(events),
{
parser: 'graphql',
},
)
}
const tsConfig = prettier.format(
JSON.stringify({
extends: '@graphprotocol/graph-ts/types/tsconfig.base.json',
include: ['src'],
}),
{ parser: 'json' },
)
// Mapping
const generateTupleFieldAssignments = ({ keyPath, index, component }) => {
let name = component.name || `value${index}`
keyPath = [...keyPath, name]
let flatName = keyPath.join('_')
let nestedName = keyPath.join('.')
return component.type === 'tuple'
? component.components.reduce(
(acc, subComponent, subIndex) =>
acc.concat(
generateTupleFieldAssignments({
keyPath,
index: subIndex,
component: subComponent,
}),
),
[],
)
: [`entity.${flatName} = event.params.${nestedName}`]
}
const generateFieldAssignment = path =>
`entity.${path.join('_')} = event.params.${path.join('.')}`
const generateFieldAssignments = ({ index, input }) =>
input.type === 'tuple'
? util
.unrollTuple({ value: input, index, path: [input.name || `param${index}`] })
.map(({ path }) => generateFieldAssignment(path))
: generateFieldAssignment([input.name || `param${index}`])
const generateEventFieldAssignments = event =>
event.inputs.reduce(
(acc, input, index) => acc.concat(generateFieldAssignments({ input, index })),
[],
)
const generateEventIndexingHandlers = (events, contractName) =>
`
import { ${events.map(
event => `${event._alias} as ${event._alias}Event`,
)}} from '../generated/${contractName}/${contractName}'
import { ${events.map(event => event._alias)} } from '../generated/schema'
${events
.map(
event =>
`
export function handle${event._alias}(event: ${event._alias}Event): void {
let entity = new ${
event._alias
}(event.transaction.hash.toHex() + '-' + event.logIndex.toString())
${generateEventFieldAssignments(event).join('\n')}
entity.save()
}
`,
)
.join('\n')}
`
const generatePlaceholderHandlers = ({ abi, events, contractName }) =>
`
import { BigInt } from '@graphprotocol/graph-ts'
import { ${contractName}, ${events.map(event => event._alias)} }
from '../generated/${contractName}/${contractName}'
import { ExampleEntity } from '../generated/schema'
${events
.map((event, index) =>
index === 0
? `
export function handle${event._alias}(event: ${event._alias}): void {
// Entities can be loaded from the store using a string ID; this ID
// needs to be unique across all entities of the same type
let entity = ExampleEntity.load(event.transaction.from.toHex())
// Entities only exist after they have been saved to the store;
// \`null\` checks allow to create entities on demand
if (!entity) {
entity = new ExampleEntity(event.transaction.from.toHex())
// Entity fields can be set using simple assignments
entity.count = BigInt.fromI32(0)
}
// BigInt and BigDecimal math are supported
entity.count = entity.count + BigInt.fromI32(1)
// Entity fields can be set based on event parameters
${generateEventFieldAssignments(event)
.slice(0, 2)
.join('\n')}
// Entities can be written to the store with \`.save()\`
entity.save()
// Note: If a handler doesn't require existing field values, it is faster
// _not_ to load the entity from the store. Instead, create it fresh with
// \`new Entity(...)\`, set the fields that should be updated and save the
// entity back to the store. Fields that were not set or unset remain
// unchanged, allowing for partial updates to be applied.
// It is also possible to access smart contracts from mappings. For
// example, the contract that has emitted the event can be connected to
// with:
//
// let contract = Contract.bind(event.address)
//
// The following functions can then be called on this contract to access
// state variables and other data:
//
// ${
abi
.codeGenerator()
.callableFunctions()
.isEmpty()
? 'None'
: abi
.codeGenerator()
.callableFunctions()
.map(fn => `- contract.${fn.get('name')}(...)`)
.join('\n// ')
}
}
`
: `
export function handle${event._alias}(event: ${event._alias}): void {}
`,
)
.join('\n')}`
const generateMapping = ({ abi, indexEvents, contractName }) => {
let events = abiEvents(abi).toJS()
return prettier.format(
indexEvents
? generateEventIndexingHandlers(events, contractName)
: generatePlaceholderHandlers({ abi, events: events, contractName }),
{ parser: 'typescript', semi: false },
)
}
const generateScaffold = async (
{ abi, address, network, subgraphName, indexEvents, contractName = 'Contract', node },
spinner,
) => {
step(spinner, 'Generate subgraph from ABI')
let packageJson = generatePackageJson({ subgraphName, node })
let manifest = generateManifest({ abi, address, network, contractName })
let schema = generateSchema({ abi, indexEvents, contractName })
let mapping = generateMapping({ abi, subgraphName, indexEvents, contractName })
return {
'package.json': packageJson,
'subgraph.yaml': manifest,
'schema.graphql': schema,
'tsconfig.json': tsConfig,
src: { 'mapping.ts': mapping },
abis: {
[`${contractName}.json`]: prettier.format(JSON.stringify(abi.data), {
parser: 'json',
}),
},
}
}
const writeScaffoldDirectory = async (scaffold, directory, spinner) => {
// Create directory itself
await fs.mkdirs(directory)
let promises = Object.keys(scaffold).map(async basename => {
let content = scaffold[basename]
let filename = path.join(directory, basename)
// Write file or recurse into subdirectory
if (typeof content === 'string') {
await fs.writeFile(filename, content, { encoding: 'utf-8' })
} else {
writeScaffoldDirectory(content, path.join(directory, basename), spinner)
}
})
await Promise.all(promises)
}
const writeScaffold = async (scaffold, directory, spinner) => {
step(spinner, `Write subgraph to directory`)
await writeScaffoldDirectory(scaffold, directory, spinner)
}
module.exports = {
...module.exports,
abiEvents,
generateEventFieldAssignments,
generateManifest,
generateMapping,
generateScaffold,
generateSchema,
writeScaffold,
}