@sentio/sdk 2.13.0-rc.1 → 2.13.0-rc.11

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 (144) hide show
  1. package/lib/aptos/aptos-chain-adapter.d.ts +14 -0
  2. package/lib/aptos/aptos-chain-adapter.js +69 -0
  3. package/lib/aptos/aptos-chain-adapter.js.map +1 -0
  4. package/lib/aptos/aptos-plugin.js +5 -2
  5. package/lib/aptos/aptos-plugin.js.map +1 -1
  6. package/lib/aptos/aptos-processor.d.ts +7 -7
  7. package/lib/aptos/aptos-processor.js +15 -22
  8. package/lib/aptos/aptos-processor.js.map +1 -1
  9. package/lib/aptos/builtin/0x1.d.ts +1138 -493
  10. package/lib/aptos/builtin/0x1.js +1939 -1458
  11. package/lib/aptos/builtin/0x1.js.map +1 -1
  12. package/lib/aptos/builtin/0x3.d.ts +227 -104
  13. package/lib/aptos/builtin/0x3.js +373 -333
  14. package/lib/aptos/builtin/0x3.js.map +1 -1
  15. package/lib/aptos/codegen/codegen.d.ts +1 -1
  16. package/lib/aptos/codegen/codegen.js +6 -47
  17. package/lib/aptos/codegen/codegen.js.map +1 -1
  18. package/lib/aptos/codegen/run.js +1 -1
  19. package/lib/aptos/codegen/run.js.map +1 -1
  20. package/lib/aptos/context.d.ts +3 -0
  21. package/lib/aptos/context.js +5 -0
  22. package/lib/aptos/context.js.map +1 -1
  23. package/lib/aptos/ext/aptos-dex.d.ts +2 -1
  24. package/lib/aptos/ext/aptos-dex.js +1 -2
  25. package/lib/aptos/ext/aptos-dex.js.map +1 -1
  26. package/lib/aptos/index.d.ts +2 -0
  27. package/lib/aptos/index.js +2 -0
  28. package/lib/aptos/index.js.map +1 -1
  29. package/lib/aptos/models.d.ts +3 -11
  30. package/lib/aptos/models.js.map +1 -1
  31. package/lib/aptos/module-client.js +1 -1
  32. package/lib/aptos/module-client.js.map +1 -1
  33. package/lib/aptos/move-coder.d.ts +10 -10
  34. package/lib/aptos/move-coder.js +37 -18
  35. package/lib/aptos/move-coder.js.map +1 -1
  36. package/lib/aptos/utils.d.ts +2 -2
  37. package/lib/aptos/utils.js +10 -7
  38. package/lib/aptos/utils.js.map +1 -1
  39. package/lib/eth/base-processor-template.d.ts +4 -3
  40. package/lib/eth/base-processor-template.js +7 -7
  41. package/lib/eth/base-processor-template.js.map +1 -1
  42. package/lib/eth/base-processor.d.ts +9 -8
  43. package/lib/eth/base-processor.js +13 -11
  44. package/lib/eth/base-processor.js.map +1 -1
  45. package/lib/eth/eth-plugin.js +8 -5
  46. package/lib/eth/eth-plugin.js.map +1 -1
  47. package/lib/eth/eth.d.ts +9 -2
  48. package/lib/eth/eth.js +23 -1
  49. package/lib/eth/eth.js.map +1 -1
  50. package/lib/move/abstract-codegen.d.ts +11 -11
  51. package/lib/move/abstract-codegen.js +59 -22
  52. package/lib/move/abstract-codegen.js.map +1 -1
  53. package/lib/move/abstract-move-coder.d.ts +19 -25
  54. package/lib/move/abstract-move-coder.js +74 -51
  55. package/lib/move/abstract-move-coder.js.map +1 -1
  56. package/lib/move/chain-adapter.d.ts +11 -0
  57. package/lib/move/chain-adapter.js +3 -0
  58. package/lib/move/chain-adapter.js.map +1 -0
  59. package/lib/move/index.d.ts +1 -0
  60. package/lib/move/index.js +1 -0
  61. package/lib/move/index.js.map +1 -1
  62. package/lib/move/types.d.ts +31 -1
  63. package/lib/move/types.js +75 -16
  64. package/lib/move/types.js.map +1 -1
  65. package/lib/move/utils.js +6 -1
  66. package/lib/move/utils.js.map +1 -1
  67. package/lib/sui/builtin/0x1.d.ts +37 -18
  68. package/lib/sui/builtin/0x1.js +58 -32
  69. package/lib/sui/builtin/0x1.js.map +1 -1
  70. package/lib/sui/builtin/0x2.d.ts +275 -125
  71. package/lib/sui/builtin/0x2.js +463 -322
  72. package/lib/sui/builtin/0x2.js.map +1 -1
  73. package/lib/sui/builtin/0x3.d.ts +135 -60
  74. package/lib/sui/builtin/0x3.js +229 -272
  75. package/lib/sui/builtin/0x3.js.map +1 -1
  76. package/lib/sui/codegen/codegen.d.ts +1 -1
  77. package/lib/sui/codegen/codegen.js +10 -36
  78. package/lib/sui/codegen/codegen.js.map +1 -1
  79. package/lib/sui/codegen/run.js +1 -1
  80. package/lib/sui/codegen/run.js.map +1 -1
  81. package/lib/sui/context.d.ts +5 -1
  82. package/lib/sui/context.js +8 -1
  83. package/lib/sui/context.js.map +1 -1
  84. package/lib/sui/index.d.ts +1 -0
  85. package/lib/sui/index.js +1 -0
  86. package/lib/sui/index.js.map +1 -1
  87. package/lib/sui/models.d.ts +3 -11
  88. package/lib/sui/models.js.map +1 -1
  89. package/lib/sui/move-coder.d.ts +15 -15
  90. package/lib/sui/move-coder.js +43 -39
  91. package/lib/sui/move-coder.js.map +1 -1
  92. package/lib/sui/sui-chain-adapter.d.ts +14 -0
  93. package/lib/sui/sui-chain-adapter.js +69 -0
  94. package/lib/sui/sui-chain-adapter.js.map +1 -0
  95. package/lib/sui/sui-plugin.js +4 -2
  96. package/lib/sui/sui-plugin.js.map +1 -1
  97. package/lib/sui/sui-processor.d.ts +6 -3
  98. package/lib/sui/sui-processor.js +23 -14
  99. package/lib/sui/sui-processor.js.map +1 -1
  100. package/lib/sui/utils.d.ts +3 -3
  101. package/lib/sui/utils.js +20 -5
  102. package/lib/sui/utils.js.map +1 -1
  103. package/lib/testing/sui-facet.d.ts +2 -2
  104. package/lib/testing/sui-facet.js +16 -26
  105. package/lib/testing/sui-facet.js.map +1 -1
  106. package/package.json +4 -4
  107. package/src/aptos/aptos-chain-adapter.ts +81 -0
  108. package/src/aptos/aptos-plugin.ts +5 -2
  109. package/src/aptos/aptos-processor.ts +35 -31
  110. package/src/aptos/builtin/0x1.ts +2742 -500
  111. package/src/aptos/builtin/0x3.ts +529 -106
  112. package/src/aptos/codegen/codegen.ts +13 -57
  113. package/src/aptos/codegen/run.ts +1 -1
  114. package/src/aptos/context.ts +5 -0
  115. package/src/aptos/ext/aptos-dex.ts +4 -12
  116. package/src/aptos/index.ts +4 -0
  117. package/src/aptos/models.ts +3 -13
  118. package/src/aptos/module-client.ts +1 -1
  119. package/src/aptos/move-coder.ts +48 -25
  120. package/src/aptos/utils.ts +11 -8
  121. package/src/eth/base-processor-template.ts +20 -10
  122. package/src/eth/base-processor.ts +45 -25
  123. package/src/eth/eth-plugin.ts +9 -6
  124. package/src/eth/eth.ts +31 -2
  125. package/src/move/abstract-codegen.ts +74 -37
  126. package/src/move/abstract-move-coder.ts +87 -75
  127. package/src/move/chain-adapter.ts +17 -0
  128. package/src/move/index.ts +1 -0
  129. package/src/move/types.ts +97 -17
  130. package/src/move/utils.ts +6 -1
  131. package/src/sui/builtin/0x1.ts +75 -20
  132. package/src/sui/builtin/0x2.ts +670 -126
  133. package/src/sui/builtin/0x3.ts +326 -61
  134. package/src/sui/codegen/codegen.ts +17 -43
  135. package/src/sui/codegen/run.ts +1 -1
  136. package/src/sui/context.ts +9 -1
  137. package/src/sui/index.ts +1 -0
  138. package/src/sui/models.ts +3 -13
  139. package/src/sui/move-coder.ts +58 -53
  140. package/src/sui/sui-chain-adapter.ts +86 -0
  141. package/src/sui/sui-plugin.ts +4 -2
  142. package/src/sui/sui-processor.ts +39 -26
  143. package/src/sui/utils.ts +25 -5
  144. package/src/testing/sui-facet.ts +15 -30
package/src/eth/eth.ts CHANGED
@@ -11,7 +11,7 @@ import {
11
11
  object,
12
12
  formatData,
13
13
  } from 'ethers/providers'
14
- import { CallExceptionError, LogDescription, Result, DeferredTopicFilter } from 'ethers'
14
+ import { CallExceptionError, LogDescription, Result, DeferredTopicFilter, BlockParams } from 'ethers'
15
15
  import { ContractContext } from './context.js'
16
16
  import { getAddress } from 'ethers/address'
17
17
  import { getBigInt, getNumber, hexlify } from 'ethers/utils'
@@ -34,6 +34,11 @@ export interface TypedEvent<TArgsArray extends Array<any> = any, TArgsObject = a
34
34
 
35
35
  export type TypedEventFilter<_TEvent extends TypedEvent> = DeferredTopicFilter
36
36
 
37
+ export interface RichBlock extends BlockParams {
38
+ traces?: Trace[]
39
+ transactionReceipts?: TransactionReceiptParams[]
40
+ }
41
+
37
42
  export class SimpleEthersError extends Error {
38
43
  e: Error
39
44
 
@@ -132,7 +137,7 @@ export function formatEthData(data: {
132
137
  if (data.block && !data.block.transactions) {
133
138
  data.block.transactions = []
134
139
  }
135
- const block = data.block ? formatBlock(data.block) : undefined
140
+ const block = data.block ? formatRichBlock(data.block) : undefined
136
141
  const trace = data.trace ? (data.trace as Trace) : undefined
137
142
  const transaction = data.transaction ? formatTransactionResponse(data.transaction) : undefined
138
143
  const transactionReceipt = data.transactionReceipt ? formatTransactionReceipt(data.transactionReceipt) : undefined
@@ -145,6 +150,14 @@ export function formatEthData(data: {
145
150
  }
146
151
  }
147
152
 
153
+ export function formatRichBlock(block: RichBlock): RichBlock {
154
+ formatBlock(block)
155
+ if (block.transactionReceipts) {
156
+ block.transactionReceipts = block.transactionReceipts.map((t) => formatTransactionReceipt(t))
157
+ }
158
+ return block
159
+ }
160
+
148
161
  export interface TypedCallTrace<TArgsArray extends Array<any> = any, TArgsObject = any> extends Trace {
149
162
  args: TArgsObject & IResult
150
163
  name: string
@@ -228,3 +241,19 @@ export interface TraceResult {
228
241
  // "transactionPosition": 22,
229
242
  // "type": "create"
230
243
  // }
244
+
245
+ export function isNullAddress(address: string) {
246
+ try {
247
+ // Normalize the input address
248
+ const normalizedAddress = getAddress(address)
249
+ // Check if the normalized address is equal to the null address (all zeros)
250
+ return normalizedAddress === '0x0000000000000000000000000000000000000000'
251
+ } catch (error) {
252
+ return false
253
+ }
254
+ }
255
+
256
+ export function validateAndNormalizeAddress(address: string): string {
257
+ const normalizedAddress = getAddress(address)
258
+ return normalizedAddress.toLowerCase()
259
+ }
@@ -12,6 +12,7 @@ import { format } from 'prettier'
12
12
  import { isFrameworkAccount, moduleQname, normalizeToJSName, SPLITTER, VECTOR_STR } from './utils.js'
13
13
  import { camelCase, upperFirst } from 'lodash-es'
14
14
  import { TypeDescriptor } from './types.js'
15
+ import { ChainAdapter } from './chain-adapter.js'
15
16
 
16
17
  interface OutputFile {
17
18
  fileName: string
@@ -24,7 +25,7 @@ interface Config<NetworkType> {
24
25
  network: NetworkType
25
26
  }
26
27
 
27
- export abstract class AbstractCodegen<ModuleTypes, NetworkType> {
28
+ export abstract class AbstractCodegen<NetworkType, ModuleTypes, StructType> {
28
29
  TEST_NET: NetworkType
29
30
  MAIN_NET: NetworkType
30
31
  ADDRESS_TYPE: string
@@ -33,30 +34,30 @@ export abstract class AbstractCodegen<ModuleTypes, NetworkType> {
33
34
  GENERATE_CLIENT = false
34
35
  GENERATE_ON_ENTRY = true
35
36
  PAYLOAD_OPTIONAL = false
37
+ SYSTEM_MODULES = new Set(['0x1', '0x2', '0x3'])
36
38
 
37
- abstract fetchModules(account: string, network: NetworkType): Promise<ModuleTypes>
38
- abstract toInternalModules(modules: ModuleTypes): InternalMoveModule[]
39
- // Get the structs that represent Events
40
- abstract getEventStructs(module: InternalMoveModule): Map<string, InternalMoveStruct>
41
- // Get the parameters that actually have arguments in runtime
42
- // Aptos first signer and Sui's last TxContext are no use
43
- abstract getMeaningfulFunctionParams(params: TypeDescriptor[]): TypeDescriptor[]
39
+ chainAdapter: ChainAdapter<NetworkType, ModuleTypes, StructType>
40
+
41
+ protected constructor(chainAdapter: ChainAdapter<NetworkType, ModuleTypes, StructType>) {
42
+ this.chainAdapter = chainAdapter
43
+ }
44
44
 
45
45
  readModulesFile(fullPath: string) {
46
46
  return JSON.parse(fs.readFileSync(fullPath, 'utf-8'))
47
47
  }
48
48
 
49
- async generate(srcDir: string, outputDir: string): Promise<number> {
50
- const num1 = await this.generateForNetwork(srcDir, outputDir, this.MAIN_NET)
49
+ async generate(srcDir: string, outputDir: string, builtin = false): Promise<number> {
50
+ const num1 = await this.generateForNetwork(srcDir, outputDir, this.MAIN_NET, builtin)
51
51
  const num2 = await this.generateForNetwork(
52
52
  path.join(srcDir, 'testnet'),
53
53
  path.join(outputDir, 'testnet'),
54
- this.TEST_NET
54
+ this.TEST_NET,
55
+ builtin
55
56
  )
56
57
  return num1 + num2
57
58
  }
58
59
 
59
- async generateForNetwork(srcDir: string, outputDir: string, network: NetworkType) {
60
+ async generateForNetwork(srcDir: string, outputDir: string, network: NetworkType, builtin = false) {
60
61
  if (!fs.existsSync(srcDir)) {
61
62
  return 0
62
63
  }
@@ -70,9 +71,9 @@ export abstract class AbstractCodegen<ModuleTypes, NetworkType> {
70
71
  const loader = new AccountRegister()
71
72
 
72
73
  // when generating user code, don't need to generate framework account
73
- loader.accountImports.set('0x1', new AccountModulesImportInfo('0x1', '0x1'))
74
- loader.accountImports.set('0x2', new AccountModulesImportInfo('0x2', '0x2'))
75
- loader.accountImports.set('0x3', new AccountModulesImportInfo('0x3', '0x3'))
74
+ for (const sysModule of this.SYSTEM_MODULES) {
75
+ loader.accountImports.set(sysModule, new AccountModulesImportInfo(sysModule, sysModule))
76
+ }
76
77
  // const client = getRpcClient(network)
77
78
 
78
79
  for (const file of files) {
@@ -81,7 +82,7 @@ export abstract class AbstractCodegen<ModuleTypes, NetworkType> {
81
82
  }
82
83
  const fullPath = path.resolve(srcDir, file)
83
84
  const abi = this.readModulesFile(fullPath)
84
- const modules = this.toInternalModules(abi)
85
+ const modules = this.chainAdapter.toInternalModules(abi)
85
86
 
86
87
  for (const module of modules) {
87
88
  loader.register(module, path.basename(file, '.json'))
@@ -100,8 +101,8 @@ export abstract class AbstractCodegen<ModuleTypes, NetworkType> {
100
101
  console.log(`download dependent module for account ${account} at ${network}`)
101
102
 
102
103
  try {
103
- const rawModules = await this.fetchModules(account, network)
104
- const modules = this.toInternalModules(rawModules)
104
+ const rawModules = await this.chainAdapter.fetchModules(account, network)
105
+ const modules = this.chainAdapter.toInternalModules(rawModules)
105
106
 
106
107
  fs.writeFileSync(path.resolve(srcDir, account + '.json'), JSON.stringify(rawModules, null, '\t'))
107
108
  for (const module of modules) {
@@ -133,18 +134,19 @@ export abstract class AbstractCodegen<ModuleTypes, NetworkType> {
133
134
  }
134
135
 
135
136
  const rootFile = path.join(outputDir, 'index.ts')
136
- fs.writeFileSync(
137
- rootFile,
138
- `/* Autogenerated file. Do not edit manually. */
137
+ let rootFileContent = `/* Autogenerated file. Do not edit manually. */
139
138
  /* tslint:disable */
140
139
  /* eslint-disable */
141
140
  `
142
- )
143
141
  for (const output of outputs) {
144
142
  const parsed = path.parse(output.fileName)
145
- const content = `export * as _${parsed.name.replaceAll('-', '_')} from './${parsed.name}.js'\n`
146
- fs.appendFileSync(rootFile, content)
143
+ rootFileContent += `export * as _${parsed.name.replaceAll('-', '_')} from './${parsed.name}.js'\n`
147
144
  }
145
+ // if (builtin) {
146
+ // rootFileContent += `export { BUILTIN_TYPES } from '@sentio/sdk/move'`
147
+ // }
148
+ fs.writeFileSync(rootFile, rootFileContent)
149
+
148
150
  return outputs.length + 1
149
151
  }
150
152
 
@@ -163,7 +165,7 @@ export abstract class AbstractCodegen<ModuleTypes, NetworkType> {
163
165
  const clientFunctions = this.GENERATE_CLIENT
164
166
  ? module.exposedFunctions.map((f) => this.generateClientFunctions(module, f)).filter((s) => s !== '')
165
167
  : []
166
- const eventStructs = this.getEventStructs(module)
168
+ const eventStructs = this.chainAdapter.getEventStructs(module)
167
169
  const eventTypes = new Set(eventStructs.keys())
168
170
  const events = Array.from(eventStructs.values())
169
171
  .map((e) => this.generateOnEvents(module, e))
@@ -219,6 +221,7 @@ export abstract class AbstractCodegen<ModuleTypes, NetworkType> {
219
221
  }
220
222
 
221
223
  generateStructs(module: InternalMoveModule, struct: InternalMoveStruct, events: Set<string>) {
224
+ const typeParams = struct.typeParams || []
222
225
  const genericString = this.generateStructTypeParameters(struct)
223
226
  const genericStringAny = this.generateStructTypeParameters(struct, true)
224
227
 
@@ -240,11 +243,34 @@ export abstract class AbstractCodegen<ModuleTypes, NetworkType> {
240
243
  `
241
244
  }
242
245
 
246
+ const typeParamApplyArg = typeParams
247
+ .map((v, idx) => {
248
+ return `arg${idx}: TypeDescriptor<T${idx}> = ANY_TYPE`
249
+ })
250
+ .join(',')
251
+ const typeParamApply = typeParams
252
+ .map((v, idx) => {
253
+ return `arg${idx}`
254
+ })
255
+ .join(',')
256
+
257
+ const typeWithArg = `
258
+ export function type${genericString}(${typeParamApplyArg}): TypeDescriptor<${structName}${genericString}> {
259
+ return TYPE.apply(${typeParamApply})
260
+ }`
261
+
243
262
  return `
244
- export class ${structName}${genericString} {
245
- static TYPE_QNAME = '${module.address}::${module.name}::${struct.name}'
263
+ export interface ${structName}${genericString} {
246
264
  ${fields.join('\n')}
247
265
  }
266
+
267
+ export namespace ${structName}{
268
+ export const TYPE_QNAME = '${module.address}::${module.name}::${struct.name}'
269
+
270
+ const TYPE = new TypeDescriptor<${structName}${genericStringAny}>(${structName}.TYPE_QNAME)
271
+
272
+ ${typeWithArg}
273
+ }
248
274
 
249
275
  ${eventPayload}
250
276
  `
@@ -282,7 +308,7 @@ export abstract class AbstractCodegen<ModuleTypes, NetworkType> {
282
308
  return
283
309
  }
284
310
 
285
- const fields = this.getMeaningfulFunctionParams(func.params).map((param) => {
311
+ const fields = this.chainAdapter.getMeaningfulFunctionParams(func.params).map((param) => {
286
312
  return this.generateTypeForDescriptor(param, module.address) + (this.PAYLOAD_OPTIONAL ? ' | undefined' : '')
287
313
  })
288
314
 
@@ -307,7 +333,7 @@ export abstract class AbstractCodegen<ModuleTypes, NetworkType> {
307
333
  }
308
334
  // const moduleName = normalizeToJSName(module.name)
309
335
  const funcName = camelCase(func.name)
310
- const fields = this.getMeaningfulFunctionParams(func.params).map((param) => {
336
+ const fields = this.chainAdapter.getMeaningfulFunctionParams(func.params).map((param) => {
311
337
  return this.generateTypeForDescriptor(param, module.address)
312
338
  })
313
339
  const genericString = this.generateFunctionTypeParameters(func)
@@ -359,7 +385,7 @@ export abstract class AbstractCodegen<ModuleTypes, NetworkType> {
359
385
  const source = `
360
386
  onEvent${struct.name}(func: (event: ${moduleName}.${normalizeToJSName(struct.name)}Instance, ctx: ${
361
387
  this.PREFIX
362
- }Context) => void, fetchConfig?: MoveFetchConfig): ${moduleName} {
388
+ }Context) => void, fetchConfig?: Partial<MoveFetchConfig>): ${moduleName} {
363
389
  this.onMoveEvent(func, {
364
390
  type: '${module.name}::${struct.name}'
365
391
  },
@@ -447,17 +473,17 @@ export abstract class AbstractCodegen<ModuleTypes, NetworkType> {
447
473
  }
448
474
  }
449
475
 
450
- export class AccountCodegen<ModuleType, NetworkType> {
476
+ export class AccountCodegen<NetworkType, ModuleType, StructType> {
451
477
  modules: InternalMoveModule[]
452
478
  config: Config<NetworkType>
453
- abi: ModuleType
479
+ abi: ModuleType[]
454
480
  loader: AccountRegister
455
- moduleGen: AbstractCodegen<ModuleType, NetworkType>
481
+ moduleGen: AbstractCodegen<NetworkType, ModuleType, StructType>
456
482
 
457
483
  constructor(
458
- moduleGen: AbstractCodegen<ModuleType, NetworkType>,
484
+ moduleGen: AbstractCodegen<NetworkType, ModuleType, StructType>,
459
485
  loader: AccountRegister,
460
- abi: ModuleType,
486
+ abi: ModuleType[],
461
487
  modules: InternalMoveModule[],
462
488
  config: Config<NetworkType>
463
489
  ) {
@@ -484,7 +510,7 @@ export class AccountCodegen<ModuleType, NetworkType> {
484
510
  }
485
511
 
486
512
  const imports = `
487
- import { CallFilter } from "@sentio/sdk/move"
513
+ import { CallFilter, TypeDescriptor, ANY_TYPE } from "@sentio/sdk/move"
488
514
  import {
489
515
  MoveCoder, defaultMoveCoder, ${this.moduleGen.PREFIX}BindOptions, ${this.moduleGen.PREFIX}BaseProcessor,
490
516
  TypedEventInstance, ${this.moduleGen.PREFIX}Network, TypedFunctionPayload,
@@ -514,6 +540,17 @@ export class AccountCodegen<ModuleType, NetworkType> {
514
540
  }
515
541
  }
516
542
 
543
+ let loadAllTypes = `loadAllTypes(defaultMoveCoder(${
544
+ this.moduleGen.PREFIX
545
+ }Network.${this.moduleGen.generateNetworkOption(this.config.network)}))`
546
+
547
+ if (this.moduleGen.SYSTEM_MODULES.has(address)) {
548
+ loadAllTypes = `
549
+ loadAllTypes(defaultMoveCoder(${this.moduleGen.PREFIX}Network.MAIN_NET))
550
+ loadAllTypes(defaultMoveCoder(${this.moduleGen.PREFIX}Network.TEST_NET))
551
+ `
552
+ }
553
+
517
554
  const source = `
518
555
  /* Autogenerated file. Do not edit manually. */
519
556
  /* tslint:disable */
@@ -536,7 +573,7 @@ export class AccountCodegen<ModuleType, NetworkType> {
536
573
  }
537
574
  }
538
575
 
539
- loadAllTypes(defaultMoveCoder())
576
+ ${loadAllTypes}
540
577
  ` // source
541
578
 
542
579
  return [
@@ -1,32 +1,25 @@
1
1
  import { moduleQname, SPLITTER, VECTOR_STR } from './utils.js'
2
- import { parseMoveType, TypeDescriptor } from './types.js'
2
+ import { DecodedStruct, matchType, parseMoveType, TypeDescriptor } from './types.js'
3
3
  import { InternalMoveFunction, InternalMoveModule, InternalMoveStruct } from './internal-models.js'
4
4
  import { bytesToBigInt } from '../utils/index.js'
5
+ import { ChainAdapter } from './chain-adapter.js'
5
6
 
6
- export type StructWithTag<Base> = {
7
- type: string
8
- data: Base
9
- }
10
-
11
- export type DecodedStructWithTag<B, T> = StructWithTag<B> & {
12
- data_decoded: T
13
- type_arguments: string[]
14
- }
15
-
16
- export abstract class AbstractMoveCoder<StructType> {
17
- private moduleMapping = new Map<string, InternalMoveModule>()
7
+ export abstract class AbstractMoveCoder<Network, ModuleType, StructType> {
8
+ protected moduleMapping = new Map<string, InternalMoveModule>()
18
9
  private typeMapping = new Map<string, InternalMoveStruct>()
19
10
  private funcMapping = new Map<string, InternalMoveFunction>()
11
+ network: Network
12
+ adapter: ChainAdapter<Network, ModuleType, StructType>
13
+
14
+ protected constructor(network: Network) {
15
+ this.network = network
16
+ }
20
17
 
21
18
  contains(account: string, name: string) {
22
19
  return this.moduleMapping.has(account + '::' + name)
23
20
  }
24
21
 
25
- protected abstract getMeaningfulFunctionParams(params: TypeDescriptor[]): TypeDescriptor[]
26
-
27
- protected toStructWithTag(val: StructType): StructWithTag<StructType> {
28
- return val as any
29
- }
22
+ abstract load(module: ModuleType): InternalMoveModule
30
23
 
31
24
  protected loadInternal(module: InternalMoveModule) {
32
25
  if (this.contains(module.address, module.name)) {
@@ -63,23 +56,53 @@ export abstract class AbstractMoveCoder<StructType> {
63
56
  return '0x' + data.toString(16)
64
57
  }
65
58
 
66
- getMoveStruct(type: string): InternalMoveStruct {
67
- const struct = this.typeMapping.get(type)
68
- if (!struct) {
69
- throw new Error('Failed to load type' + type + ' type are not imported anywhere')
59
+ private requestMap = new Map<string, Promise<InternalMoveModule>>()
60
+
61
+ async getMoveStruct(type: string): Promise<InternalMoveStruct> {
62
+ let struct = this.typeMapping.get(type)
63
+ if (struct) {
64
+ return struct
65
+ }
66
+ const [account, module, typeName] = type.split(SPLITTER)
67
+ const key = account + SPLITTER + module
68
+ let resp = this.requestMap.get(account + SPLITTER + module)
69
+ if (!resp) {
70
+ resp = this.adapter.fetchModule(account, module, this.network).then((m) => {
71
+ return this.load(m)
72
+ })
73
+ this.requestMap.set(key, resp)
70
74
  }
71
- return struct
75
+ await resp
76
+ struct = this.typeMapping.get(type)
77
+ if (struct) {
78
+ return struct
79
+ }
80
+ throw new Error('Failed to load function ' + type + ' type are not imported anywhere')
72
81
  }
73
82
 
74
- getMoveFunction(type: string): InternalMoveFunction {
75
- const func = this.funcMapping.get(type)
76
- if (!func) {
77
- throw new Error('Failed to load function ' + type + ' type are not imported anywhere')
83
+ async getMoveFunction(type: string): Promise<InternalMoveFunction> {
84
+ let func = this.funcMapping.get(type)
85
+ if (func) {
86
+ return func
87
+ }
88
+ const [account, module, typeName] = type.split(SPLITTER)
89
+ const key = account + SPLITTER + module
90
+ let resp = this.requestMap.get(account + SPLITTER + module)
91
+ if (!resp) {
92
+ resp = this.adapter.fetchModule(account, module, this.network).then((m) => {
93
+ return this.load(m)
94
+ })
95
+ this.requestMap.set(key, resp)
96
+ }
97
+ await resp
98
+ func = this.funcMapping.get(type)
99
+ if (func) {
100
+ return func
78
101
  }
79
- return func
102
+ throw new Error('Failed to load function ' + type + ' type are not imported anywhere')
80
103
  }
81
104
 
82
- decode(data: any, type: TypeDescriptor): any {
105
+ async decode(data: any, type: TypeDescriptor): Promise<any> {
83
106
  // process simple type
84
107
  if (type.reference) {
85
108
  return data
@@ -114,13 +137,13 @@ export abstract class AbstractMoveCoder<StructType> {
114
137
 
115
138
  const res = []
116
139
  for (const entry of data) {
117
- res.push(this.decode(entry, type.typeArgs[0]))
140
+ res.push(await this.decode(entry, type.typeArgs[0]))
118
141
  }
119
142
  return res
120
143
  }
121
144
 
122
145
  // Process complex type
123
- const struct = this.getMoveStruct(type.qname)
146
+ const struct = await this.getMoveStruct(type.qname)
124
147
 
125
148
  const typeCtx = new Map<string, TypeDescriptor>()
126
149
  for (const [idx, typeArg] of type.typeArgs.entries()) {
@@ -132,13 +155,14 @@ export abstract class AbstractMoveCoder<StructType> {
132
155
  for (const field of struct.fields) {
133
156
  let filedType = field.type
134
157
  filedType = filedType.applyTypeArgs(typeCtx)
135
- const value = this.decode(data[field.name], filedType)
158
+ const fieldValue = this.adapter.getData(data)[field.name]
159
+ const value = await this.decode(fieldValue, filedType)
136
160
  typedData[field.name] = value
137
161
  }
138
162
  return typedData
139
163
  }
140
164
 
141
- encode(data: any, type: TypeDescriptor): any {
165
+ async encode(data: any, type: TypeDescriptor): Promise<any> {
142
166
  // process simple type
143
167
  if (type.reference) {
144
168
  return data
@@ -183,7 +207,7 @@ export abstract class AbstractMoveCoder<StructType> {
183
207
  }
184
208
 
185
209
  // Process complex type
186
- const struct = this.getMoveStruct(type.qname)
210
+ const struct = await this.getMoveStruct(type.qname)
187
211
 
188
212
  const typeCtx = new Map<string, TypeDescriptor>()
189
213
  for (const [idx, typeArg] of type.typeArgs.entries()) {
@@ -195,19 +219,19 @@ export abstract class AbstractMoveCoder<StructType> {
195
219
  for (const field of struct.fields) {
196
220
  let filedType = field.type
197
221
  filedType = filedType.applyTypeArgs(typeCtx)
198
- const value = this.encode(data[field.name], filedType)
222
+ const value = await this.encode(data[field.name], filedType)
199
223
  typedData[field.name] = value
200
224
  }
201
225
  return typedData
202
226
  }
203
227
 
204
- decodeArray(entries: any[], types: TypeDescriptor[]): any[] {
228
+ async decodeArray(entries: any[], types: TypeDescriptor[]): Promise<any[]> {
205
229
  const entriesDecoded: any[] = []
206
230
  for (const [idx, arg] of entries.entries()) {
207
231
  // TODO consider apply payload.type_arguments, but this might be hard since we don't code gen for them
208
232
  const argType = types[idx]
209
233
  try {
210
- entriesDecoded.push(this.decode(arg, argType))
234
+ entriesDecoded.push(await this.decode(arg, argType))
211
235
  } catch (e) {
212
236
  console.error(e, 'Decoding error for ', JSON.stringify(arg), 'using type', argType)
213
237
  return entries
@@ -216,13 +240,13 @@ export abstract class AbstractMoveCoder<StructType> {
216
240
  return entriesDecoded
217
241
  }
218
242
 
219
- encodeArray(entriesDecoded: any[], types: TypeDescriptor[]): any[] {
243
+ async encodeArray(entriesDecoded: any[], types: TypeDescriptor[]): Promise<any[]> {
220
244
  const entries: any[] = []
221
245
  for (const [idx, arg] of entriesDecoded.entries()) {
222
246
  // TODO consider apply payload.type_arguments, but this might be hard since we don't code gen for them
223
247
  const argType = types[idx]
224
248
  try {
225
- entries.push(this.encode(arg, argType))
249
+ entries.push(await this.encode(arg, argType))
226
250
  } catch (e) {
227
251
  throw Error('Decoding error for ' + JSON.stringify(arg) + 'using type' + argType + e.toString())
228
252
  }
@@ -230,61 +254,49 @@ export abstract class AbstractMoveCoder<StructType> {
230
254
  return entries
231
255
  }
232
256
 
233
- encodeCallArgs(args: any[], func: string): any[] {
234
- const f = this.getMoveFunction(func)
235
- return this.encodeArray(args, this.getMeaningfulFunctionParams(f.params))
257
+ async encodeCallArgs(args: any[], func: string): Promise<any[]> {
258
+ const f = await this.getMoveFunction(func)
259
+ return this.encodeArray(args, this.adapter.getMeaningfulFunctionParams(f.params))
236
260
  }
237
261
 
238
- decodeCallResult(res: any[], func: string): any[] {
239
- const f = this.getMoveFunction(func)
262
+ async decodeCallResult(res: any[], func: string): Promise<any[]> {
263
+ const f = await this.getMoveFunction(func)
240
264
  return this.decodeArray(res, f.return)
241
265
  }
242
266
 
243
- protected filterAndDecodeStruct(typeQname: string, structs: StructType[]): any {
244
- if (!structs) {
245
- return []
246
- }
247
- const withTags = structs.map((s) => this.toStructWithTag(s))
248
- return this.filterAndDecodeStructWithTags(typeQname, withTags)
249
- }
250
-
251
- private filterAndDecodeStructWithTags<T>(
252
- typeQname: string,
253
- structsWithTags: StructWithTag<StructType>[]
254
- ): DecodedStructWithTag<StructType, T>[] {
267
+ protected async filterAndDecodeStruct<T>(
268
+ typeMatcher: TypeDescriptor<T>,
269
+ structsWithTags: StructType[]
270
+ ): Promise<DecodedStruct<StructType, T>[]> {
255
271
  if (!structsWithTags) {
256
- return []
272
+ return [] as any
257
273
  }
258
- const results: DecodedStructWithTag<StructType, T>[] = []
274
+ // const typeMatcherDescriptor = parseMoveType(typeMatcher)
275
+ const results: DecodedStruct<StructType, T>[] = []
259
276
  for (const resource of structsWithTags) {
260
- if (typeQname.includes('<')) {
261
- if (resource.type !== typeQname) {
262
- continue
263
- }
264
- } else if (resource.type.split('<')[0] !== typeQname) {
277
+ const resourceType = this.adapter.getType(resource)
278
+ const resourceTypeDescriptor = parseMoveType(resourceType)
279
+ if (!matchType(typeMatcher, resourceTypeDescriptor)) {
265
280
  continue
266
281
  }
267
- const result = this.decodedStructWithTag(resource)
282
+
283
+ const result = await this.decodedStruct<T>(resource)
268
284
  if (result) {
269
- results.push(result as DecodedStructWithTag<StructType, T>)
285
+ results.push(result)
286
+ } else {
287
+ console.error('decoding error')
270
288
  }
271
289
  }
272
290
  return results
273
291
  }
274
292
 
275
- protected decodedStruct<T>(typeStruct: StructType): DecodedStructWithTag<StructType, T> | undefined {
276
- return this.decodedStructWithTag(this.toStructWithTag(typeStruct)) as any
277
- }
278
-
279
- private decodedStructWithTag<T>(
280
- typeStruct: StructWithTag<StructType>
281
- ): DecodedStructWithTag<StructType, T> | undefined {
282
- const typeDescriptor = parseMoveType(typeStruct.type)
293
+ protected async decodedStruct<T>(typeStruct: StructType): Promise<DecodedStruct<StructType, T> | undefined> {
294
+ const typeDescriptor = parseMoveType(this.adapter.getType(typeStruct))
283
295
  const typeArguments = typeDescriptor.typeArgs.map((t) => t.getSignature())
284
296
 
285
297
  let dataTyped = undefined
286
298
  try {
287
- dataTyped = this.decode(this.toStructWithTag(typeStruct.data), typeDescriptor)
299
+ dataTyped = await this.decode(typeStruct, typeDescriptor)
288
300
  } catch (e) {
289
301
  console.error('Decoding error for ', JSON.stringify(typeStruct), e)
290
302
  return undefined
@@ -293,6 +305,6 @@ export abstract class AbstractMoveCoder<StructType> {
293
305
  ...typeStruct,
294
306
  data_decoded: dataTyped,
295
307
  type_arguments: typeArguments,
296
- } as DecodedStructWithTag<StructType, T>
308
+ } as DecodedStruct<StructType, T>
297
309
  }
298
310
  }
@@ -0,0 +1,17 @@
1
+ import { InternalMoveModule, InternalMoveStruct } from './internal-models.js'
2
+ import { TypeDescriptor } from './types.js'
3
+
4
+ export abstract class ChainAdapter<NetworkType, ModuleType, StructType> {
5
+ abstract fetchModule(account: string, module: string, network: NetworkType): Promise<ModuleType>
6
+
7
+ abstract fetchModules(account: string, network: NetworkType): Promise<ModuleType[]>
8
+ abstract toInternalModules(modules: ModuleType[]): InternalMoveModule[]
9
+ // Get the structs that represent Events
10
+ abstract getEventStructs(module: InternalMoveModule): Map<string, InternalMoveStruct>
11
+ // Get the parameters that actually have arguments in runtime
12
+ // Aptos first signer and Sui's last TxContext are no use
13
+ abstract getMeaningfulFunctionParams(params: TypeDescriptor[]): TypeDescriptor[]
14
+
15
+ abstract getType(base: StructType): string
16
+ abstract getData<T>(base: StructType): any
17
+ }
package/src/move/index.ts CHANGED
@@ -2,3 +2,4 @@ export * from './filter.js'
2
2
  export * from './types.js'
3
3
  export * from './utils.js'
4
4
  export * from './account.js'
5
+ export * from './chain-adapter.js'