-
Notifications
You must be signed in to change notification settings - Fork 353
/
StarknetTarget.ts
288 lines (248 loc) 路 8.82 KB
/
StarknetTarget.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
import { uniqBy, zip } from 'lodash'
import { join, relative, resolve } from 'path'
import { Abi, AbiEntry, FunctionAbi, json, number, StructAbi } from 'starknet'
// import { AbiEntry, StructAbi } from 'starknet/types/lib'
import {
Config,
FileDescription,
normalizeSlashes,
Output,
parseContractPath,
shortenFullJsonFilePath,
TypeChainTarget,
} from 'typechain'
import { importer } from './importer'
const DEFAULT_OUT_PATH = './types/starknet-contracts/'
export class StarknetTarget extends TypeChainTarget {
name = 'StarknetTarget'
private readonly allFiles: string[]
private readonly outDirAbs: string
constructor(config: Config) {
super(config)
const { cwd, outDir, allFiles } = config
this.allFiles = allFiles
.map((p) => shortenFullJsonFilePath(p, allFiles))
.map((p) => relative(this.cfg.inputDir, p))
.map(normalizeSlashes)
this.outDirAbs = resolve(cwd, outDir || DEFAULT_OUT_PATH)
}
transformFile(file: FileDescription): Output {
const compiled = json.parse(file.contents)
const name = parseContractPath(file.path).rawName
const {
structTypes,
// constructorArgs,
functions,
imports,
impoort,
} = transformer(compiled.abi)
const ContractInterface = impoort('starknet', 'Contract')
// const ContractFactory = impoort('starknet', 'ContractFactory')
// const Contract = impoort('starknet', 'Contract')
// const contractFactory = `
// export interface ${name}Factory extends ${ContractFactory} {
// async deploy(
// constructorCalldata?: [${constructorArgs()}],
// addressSalt?: BigNumberish
// ): Promise<${Contract}>
// }
// `
const resultWithoutImports = `
${structTypes()}
export interface ${name} extends ${ContractInterface} {
${functions('default').join('\n')}
functions: {
${functions('default').join('\n')}
}
callStatic: {
${functions('call').join('\n')}
}
populateTransaction: {
${functions('populate').join('\n')}
}
estimateFee: {
${functions('estimate').join('\n')}
}
}
`
const temporaryAliases = [
resultWithoutImports.indexOf('options?: CallOptions') >= 0
? 'type CallOptions = { blockIdentifier: EstimateFeeDetails["blockIdentifier"] }'
: '',
resultWithoutImports.indexOf('BigNumberish') >= 0 ? 'type BigNumberish = number.BigNumberish' : '',
resultWithoutImports.indexOf('BN') >= 0 ? 'type BN = ReturnType<typeof number.toBN>' : '',
].join('\n')
const result = `
${imports()}
${temporaryAliases}
${resultWithoutImports}
`
return {
contents: result,
path: join(this.outDirAbs, `${name}.ts`), // @todo fix, should have same behaviour as in other plugins
}
}
override afterRun(): FileDescription[] {
const index = {
path: join(this.outDirAbs, 'index.ts'),
contents: createIndexContents(this.allFiles),
}
return [index]
}
}
type DeclarationType = 'default' | 'call' | 'populate' | 'estimate'
type AbiEntriesByName = Map<string, FunctionAbi | StructAbi>
function byName(abi: Abi): AbiEntriesByName {
return abi.reduce((r, e) => r.set(e.name, e), new Map<string, FunctionAbi | StructAbi>())
}
type Direction = 'input' | 'output'
function transformer(rawAbi: Abi) {
const abi = byName(rawAbi)
const { imports, impoort } = importer()
function constructorArgs(): string {
const constructorAbi: FunctionAbi | undefined = [...(abi.values() as any)].find((e) => e.type === 'constructor')
return constructorAbi ? entriesTypesOnly(constructorAbi.inputs, 'input') : ''
}
function options(e: FunctionAbi, returnType: DeclarationType): string {
// TODO: Why estimate takes blockIdentifier?
if ((returnType === 'populate' || returnType === 'default') && e.stateMutability !== 'view') {
const Overrides = impoort('starknet', 'Overrides')
return `options?: ${Overrides}`
}
// const CallOptions = impoort('starknet', 'CallOptions')
impoort('starknet', 'EstimateFeeDetails')
return `options?: CallOptions`
}
function functions(returnType: DeclarationType): string[] {
return [...(abi.values() as any)] // @todo fix any
.filter((e) => e.type === 'function') // && e.stateMutability === "view"
.map((e: FunctionAbi) => {
const args = entries(e.inputs, 'input')
const opts = options(e, returnType)
const rets = returns(e, returnType)
return `${e.name}(${args}${args !== '' ? ', ' : ''}${opts}):${rets}`
})
}
// function generateEventTypes(): string {
// const events = [...(abi.values() as any)] // @todo fix any
// .filter((e) => e.type === 'event');
// return events.map(e =>
// `export type ${e.name} = {
// ${entriesToInterface(e.data)}\n
// }`
// ).join('\n');
// }
function structTypes(): string {
const structs = [...(abi.values() as any)] // @todo fix any
.filter((e) => e.type === 'struct')
const namedStructs = structs.filter((s) => !!s.name)
return namedStructs
.map((s) => {
return `
export type ${s.name} = { ${entriesToInterface(s.members, 'input')}\n }
export type ${s.name}Output = { ${entriesToInterface(s.members, 'output')}\n }
`
})
.join('\n')
}
function viewType(e: FunctionAbi, dir: Direction) {
return `[${entriesTypesOnly(e.outputs, dir)}] & {${entries(e.outputs, dir)}}`
}
function returns(e: FunctionAbi, returnType: DeclarationType): string {
switch (returnType) {
case 'default':
return e.stateMutability === 'view'
? `Promise<${viewType(e, 'output')}>`
: `Promise<${impoort('starknet', 'InvokeTransactionResponse')}>`
case 'call':
return `Promise<${viewType(e, 'output')}>`
case 'populate':
return `${impoort('starknet', 'Invocation')}`
case 'estimate':
return `Promise<${impoort('starknet', 'EstimateFeeResponse')}>`
}
}
function entriesPairs(abiEntries: AbiEntry[], dir: Direction) {
if (abiEntries.length === 0) {
return []
}
return zip(abiEntries, abiEntries.slice(1), [undefined, ...abiEntries.slice(0, -1)])
.filter(([e, n]) => !(n && `${n.name}_len` === e!.name && n.type.slice(-1) === '*'))
.map(
(
[e, _, p], // @todo fix !
) =>
p && `${e!.name}_len` === p.name && e!.type.slice(-1) === '*'
? [`${e!.name}`, `${mapType(e!.type.slice(0, -1), dir)}[]`]
: [`${e!.name}`, `${mapType(e!.type, dir)}`],
)
}
function entries(abiEntries: AbiEntry[], dir: Direction) {
return entriesPairs(abiEntries, dir)
.map(([name, type]) => `${name}: ${type}`)
.join(', ')
}
function entriesToInterface(abiEntries: AbiEntry[], dir: Direction) {
return entriesPairs(abiEntries, dir)
.map(([name, type]) => `${name}: ${type}`)
.join(';\n')
}
function entriesTypesOnly(abiEntries: AbiEntry[], dir: Direction) {
return entriesPairs(abiEntries, dir)
.map(([_, type]) => `${type}`)
.join(', ')
}
const tuple = /\(([^,]+)(, ([^,]+))*\)/
const space = /\s/g
function mapType(type: AbiEntry['type'], dir: Direction): string {
if (type === 'felt') {
if (dir === 'input') {
return impoort('starknet', 'number', 'BigNumberish')
} else {
return impoort('starknet', 'number', 'BN')
}
}
// Disabled as this feature is not yet available in starknet.js
// if (type === 'Uint256') {
// const entry = abi.get(type)! // @todo undefined
// if (entry.type === 'struct' &&
// entry.members.length === 2 &&
// entry.members[0].name === 'low' && entry.members[0].type === 'felt' &&
// entry.members[1].name === 'high' && entry.members[1].type === 'felt'
// ) {
// return impoort('starknet/utils/number', 'BigNumberish')
// }
// }
if (tuple.test(type)) {
const types = type.slice(1, -1).replace(space, '').split(',')
return `[${types.map((t) => mapType(t, dir)).join(', ')}]`
}
if (abi.has(type)) {
const entry = abi.get(type)! // @todo undefined
if (entry.type === 'struct') {
if (dir === 'input') {
return `${entry.name}`
} else {
return `${entry.name}Output`
}
}
}
return type
}
return {
structTypes,
constructorArgs,
functions,
imports,
impoort,
}
}
function createIndexContents(paths: string[]) {
const contracts: { path: string[]; rawName: string }[] = paths.map(parseContractPath)
return uniqBy(Object.values(contracts), (c) => c.rawName)
.flatMap((c) => {
const path = c.path.length === 0 ? c.rawName : `${c.path.join('/')}/${c.rawName}`
return [`export type { ${c.rawName} } from './${path}';`]
})
.join('\n')
}