@ledgerhq/context-module 1.6.0 → 1.7.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 (165) hide show
  1. package/lib/cjs/package.json +1 -1
  2. package/lib/cjs/src/ContextModuleBuilder.js +1 -1
  3. package/lib/cjs/src/ContextModuleBuilder.js.map +3 -3
  4. package/lib/cjs/src/ContextModuleBuilder.test.js +1 -1
  5. package/lib/cjs/src/ContextModuleBuilder.test.js.map +2 -2
  6. package/lib/cjs/src/DefaultContextModule.js +1 -1
  7. package/lib/cjs/src/DefaultContextModule.js.map +3 -3
  8. package/lib/cjs/src/DefaultContextModule.test.js +1 -1
  9. package/lib/cjs/src/DefaultContextModule.test.js.map +2 -2
  10. package/lib/cjs/src/config/model/ContextModuleConfig.js +1 -1
  11. package/lib/cjs/src/config/model/ContextModuleConfig.js.map +1 -1
  12. package/lib/cjs/src/di.js +1 -1
  13. package/lib/cjs/src/di.js.map +3 -3
  14. package/lib/cjs/src/dynamic-network/data/DynamicNetworkDataSource.js +2 -0
  15. package/lib/cjs/src/dynamic-network/data/DynamicNetworkDataSource.js.map +7 -0
  16. package/lib/cjs/src/dynamic-network/data/HttpDynamicNetworkDataSource.js +2 -0
  17. package/lib/cjs/src/dynamic-network/data/HttpDynamicNetworkDataSource.js.map +7 -0
  18. package/lib/cjs/src/dynamic-network/data/HttpDynamicNetworkDataSource.test.js +2 -0
  19. package/lib/cjs/src/dynamic-network/data/HttpDynamicNetworkDataSource.test.js.map +7 -0
  20. package/lib/cjs/src/dynamic-network/data/dto/DynamicNetworkApiResponseDto.js +2 -0
  21. package/lib/cjs/src/dynamic-network/data/dto/DynamicNetworkApiResponseDto.js.map +7 -0
  22. package/lib/cjs/src/dynamic-network/di/dynamicNetworkModuleFactory.js +2 -0
  23. package/lib/cjs/src/dynamic-network/di/dynamicNetworkModuleFactory.js.map +7 -0
  24. package/lib/cjs/src/dynamic-network/di/dynamicNetworkTypes.js +2 -0
  25. package/lib/cjs/src/dynamic-network/di/dynamicNetworkTypes.js.map +7 -0
  26. package/lib/cjs/src/dynamic-network/domain/DynamicNetworkContextLoader.js +2 -0
  27. package/lib/cjs/src/dynamic-network/domain/DynamicNetworkContextLoader.js.map +7 -0
  28. package/lib/cjs/src/dynamic-network/domain/DynamicNetworkContextLoader.test.js +2 -0
  29. package/lib/cjs/src/dynamic-network/domain/DynamicNetworkContextLoader.test.js.map +7 -0
  30. package/lib/cjs/src/dynamic-network/model/DynamicNetworkConfiguration.js +2 -0
  31. package/lib/cjs/src/dynamic-network/model/DynamicNetworkConfiguration.js.map +7 -0
  32. package/lib/cjs/src/external-plugin/domain/ExternalPluginContextLoader.test.js +1 -1
  33. package/lib/cjs/src/external-plugin/domain/ExternalPluginContextLoader.test.js.map +2 -2
  34. package/lib/cjs/src/index.js +1 -1
  35. package/lib/cjs/src/index.js.map +2 -2
  36. package/lib/cjs/src/nft/data/HttpNftDataSource.js +1 -1
  37. package/lib/cjs/src/nft/data/HttpNftDataSource.js.map +2 -2
  38. package/lib/cjs/src/nft/data/HttpNftDataSource.test.js +1 -1
  39. package/lib/cjs/src/nft/data/HttpNftDataSource.test.js.map +2 -2
  40. package/lib/cjs/src/pki/domain/DefaultPkiCertificateLoader.js +1 -1
  41. package/lib/cjs/src/pki/domain/DefaultPkiCertificateLoader.js.map +3 -3
  42. package/lib/cjs/src/pki/domain/DefaultPkiCertificateLoader.test.js +1 -1
  43. package/lib/cjs/src/pki/domain/DefaultPkiCertificateLoader.test.js.map +3 -3
  44. package/lib/cjs/src/shared/model/ClearSignContext.js +1 -1
  45. package/lib/cjs/src/shared/model/ClearSignContext.js.map +2 -2
  46. package/lib/cjs/src/solana/data/HttpSolanaOwnerInfoDataSource.js +1 -1
  47. package/lib/cjs/src/solana/data/HttpSolanaOwnerInfoDataSource.js.map +2 -2
  48. package/lib/cjs/src/solana/data/HttpSolanaOwnerInfoDataSource.test.js +1 -1
  49. package/lib/cjs/src/solana/data/HttpSolanaOwnerInfoDataSource.test.js.map +2 -2
  50. package/lib/cjs/src/transaction/data/HttpProxyDataSource.js +1 -1
  51. package/lib/cjs/src/transaction/data/HttpProxyDataSource.js.map +3 -3
  52. package/lib/cjs/src/transaction/data/HttpProxyDataSource.test.js +1 -1
  53. package/lib/cjs/src/transaction/data/HttpProxyDataSource.test.js.map +2 -2
  54. package/lib/cjs/src/transaction/data/dto/ProxyDelegateCallDto.js +1 -1
  55. package/lib/cjs/src/transaction/data/dto/ProxyDelegateCallDto.js.map +1 -1
  56. package/lib/cjs/src/transaction/domain/TransactionContextLoader.js +1 -1
  57. package/lib/cjs/src/transaction/domain/TransactionContextLoader.js.map +3 -3
  58. package/lib/cjs/src/transaction/domain/TransactionContextLoader.test.js +1 -1
  59. package/lib/cjs/src/transaction/domain/TransactionContextLoader.test.js.map +3 -3
  60. package/lib/cjs/src/trusted-name/data/HttpTrustedNameDataSource.js +1 -1
  61. package/lib/cjs/src/trusted-name/data/HttpTrustedNameDataSource.js.map +2 -2
  62. package/lib/cjs/src/trusted-name/data/HttpTrustedNameDataSource.test.js +1 -1
  63. package/lib/cjs/src/trusted-name/data/HttpTrustedNameDataSource.test.js.map +2 -2
  64. package/lib/cjs/src/trusted-name/domain/TrustedNameContextLoader.test.js +1 -1
  65. package/lib/cjs/src/trusted-name/domain/TrustedNameContextLoader.test.js.map +2 -2
  66. package/lib/cjs/src/uniswap/domain/UniswapContextLoader.js +1 -1
  67. package/lib/cjs/src/uniswap/domain/UniswapContextLoader.js.map +2 -2
  68. package/lib/esm/package.json +1 -1
  69. package/lib/esm/src/ContextModuleBuilder.js +1 -1
  70. package/lib/esm/src/ContextModuleBuilder.js.map +3 -3
  71. package/lib/esm/src/ContextModuleBuilder.test.js +1 -1
  72. package/lib/esm/src/ContextModuleBuilder.test.js.map +2 -2
  73. package/lib/esm/src/DefaultContextModule.js +1 -1
  74. package/lib/esm/src/DefaultContextModule.js.map +3 -3
  75. package/lib/esm/src/DefaultContextModule.test.js +1 -1
  76. package/lib/esm/src/DefaultContextModule.test.js.map +2 -2
  77. package/lib/esm/src/di.js +1 -1
  78. package/lib/esm/src/di.js.map +3 -3
  79. package/lib/esm/src/dynamic-network/data/DynamicNetworkDataSource.js +1 -0
  80. package/lib/esm/src/dynamic-network/data/DynamicNetworkDataSource.js.map +7 -0
  81. package/lib/esm/src/dynamic-network/data/HttpDynamicNetworkDataSource.js +2 -0
  82. package/lib/esm/src/dynamic-network/data/HttpDynamicNetworkDataSource.js.map +7 -0
  83. package/lib/esm/src/dynamic-network/data/HttpDynamicNetworkDataSource.test.js +2 -0
  84. package/lib/esm/src/dynamic-network/data/HttpDynamicNetworkDataSource.test.js.map +7 -0
  85. package/lib/esm/src/dynamic-network/data/dto/DynamicNetworkApiResponseDto.js +1 -0
  86. package/lib/esm/src/dynamic-network/data/dto/DynamicNetworkApiResponseDto.js.map +7 -0
  87. package/lib/esm/src/dynamic-network/di/dynamicNetworkModuleFactory.js +2 -0
  88. package/lib/esm/src/dynamic-network/di/dynamicNetworkModuleFactory.js.map +7 -0
  89. package/lib/esm/src/dynamic-network/di/dynamicNetworkTypes.js +2 -0
  90. package/lib/esm/src/dynamic-network/di/dynamicNetworkTypes.js.map +7 -0
  91. package/lib/esm/src/dynamic-network/domain/DynamicNetworkContextLoader.js +2 -0
  92. package/lib/esm/src/dynamic-network/domain/DynamicNetworkContextLoader.js.map +7 -0
  93. package/lib/esm/src/dynamic-network/domain/DynamicNetworkContextLoader.test.js +2 -0
  94. package/lib/esm/src/dynamic-network/domain/DynamicNetworkContextLoader.test.js.map +7 -0
  95. package/lib/esm/src/dynamic-network/model/DynamicNetworkConfiguration.js +1 -0
  96. package/lib/esm/src/dynamic-network/model/DynamicNetworkConfiguration.js.map +7 -0
  97. package/lib/esm/src/external-plugin/domain/ExternalPluginContextLoader.test.js +1 -1
  98. package/lib/esm/src/external-plugin/domain/ExternalPluginContextLoader.test.js.map +2 -2
  99. package/lib/esm/src/index.js +1 -1
  100. package/lib/esm/src/index.js.map +2 -2
  101. package/lib/esm/src/nft/data/HttpNftDataSource.js +1 -1
  102. package/lib/esm/src/nft/data/HttpNftDataSource.js.map +2 -2
  103. package/lib/esm/src/nft/data/HttpNftDataSource.test.js +1 -1
  104. package/lib/esm/src/nft/data/HttpNftDataSource.test.js.map +2 -2
  105. package/lib/esm/src/pki/domain/DefaultPkiCertificateLoader.js +1 -1
  106. package/lib/esm/src/pki/domain/DefaultPkiCertificateLoader.js.map +3 -3
  107. package/lib/esm/src/pki/domain/DefaultPkiCertificateLoader.test.js +1 -1
  108. package/lib/esm/src/pki/domain/DefaultPkiCertificateLoader.test.js.map +3 -3
  109. package/lib/esm/src/shared/model/ClearSignContext.js +1 -1
  110. package/lib/esm/src/shared/model/ClearSignContext.js.map +2 -2
  111. package/lib/esm/src/solana/data/HttpSolanaOwnerInfoDataSource.js +1 -1
  112. package/lib/esm/src/solana/data/HttpSolanaOwnerInfoDataSource.js.map +2 -2
  113. package/lib/esm/src/solana/data/HttpSolanaOwnerInfoDataSource.test.js +1 -1
  114. package/lib/esm/src/solana/data/HttpSolanaOwnerInfoDataSource.test.js.map +2 -2
  115. package/lib/esm/src/transaction/data/HttpProxyDataSource.js +1 -1
  116. package/lib/esm/src/transaction/data/HttpProxyDataSource.js.map +3 -3
  117. package/lib/esm/src/transaction/data/HttpProxyDataSource.test.js +1 -1
  118. package/lib/esm/src/transaction/data/HttpProxyDataSource.test.js.map +2 -2
  119. package/lib/esm/src/transaction/domain/TransactionContextLoader.js +1 -1
  120. package/lib/esm/src/transaction/domain/TransactionContextLoader.js.map +3 -3
  121. package/lib/esm/src/transaction/domain/TransactionContextLoader.test.js +1 -1
  122. package/lib/esm/src/transaction/domain/TransactionContextLoader.test.js.map +3 -3
  123. package/lib/esm/src/trusted-name/data/HttpTrustedNameDataSource.js +1 -1
  124. package/lib/esm/src/trusted-name/data/HttpTrustedNameDataSource.js.map +2 -2
  125. package/lib/esm/src/trusted-name/data/HttpTrustedNameDataSource.test.js +1 -1
  126. package/lib/esm/src/trusted-name/data/HttpTrustedNameDataSource.test.js.map +2 -2
  127. package/lib/esm/src/trusted-name/domain/TrustedNameContextLoader.test.js +1 -1
  128. package/lib/esm/src/trusted-name/domain/TrustedNameContextLoader.test.js.map +2 -2
  129. package/lib/esm/src/uniswap/domain/UniswapContextLoader.js +1 -1
  130. package/lib/esm/src/uniswap/domain/UniswapContextLoader.js.map +2 -2
  131. package/lib/types/src/DefaultContextModule.d.ts.map +1 -1
  132. package/lib/types/src/config/model/ContextModuleConfig.d.ts +1 -1
  133. package/lib/types/src/config/model/ContextModuleConfig.d.ts.map +1 -1
  134. package/lib/types/src/di.d.ts.map +1 -1
  135. package/lib/types/src/dynamic-network/data/DynamicNetworkDataSource.d.ts +6 -0
  136. package/lib/types/src/dynamic-network/data/DynamicNetworkDataSource.d.ts.map +1 -0
  137. package/lib/types/src/dynamic-network/data/HttpDynamicNetworkDataSource.d.ts +13 -0
  138. package/lib/types/src/dynamic-network/data/HttpDynamicNetworkDataSource.d.ts.map +1 -0
  139. package/lib/types/src/dynamic-network/data/HttpDynamicNetworkDataSource.test.d.ts +2 -0
  140. package/lib/types/src/dynamic-network/data/HttpDynamicNetworkDataSource.test.d.ts.map +1 -0
  141. package/lib/types/src/dynamic-network/data/dto/DynamicNetworkApiResponseDto.d.ts +14 -0
  142. package/lib/types/src/dynamic-network/data/dto/DynamicNetworkApiResponseDto.d.ts.map +1 -0
  143. package/lib/types/src/dynamic-network/di/dynamicNetworkModuleFactory.d.ts +3 -0
  144. package/lib/types/src/dynamic-network/di/dynamicNetworkModuleFactory.d.ts.map +1 -0
  145. package/lib/types/src/dynamic-network/di/dynamicNetworkTypes.d.ts +5 -0
  146. package/lib/types/src/dynamic-network/di/dynamicNetworkTypes.d.ts.map +1 -0
  147. package/lib/types/src/dynamic-network/domain/DynamicNetworkContextLoader.d.ts +15 -0
  148. package/lib/types/src/dynamic-network/domain/DynamicNetworkContextLoader.d.ts.map +1 -0
  149. package/lib/types/src/dynamic-network/domain/DynamicNetworkContextLoader.test.d.ts +2 -0
  150. package/lib/types/src/dynamic-network/domain/DynamicNetworkContextLoader.test.d.ts.map +1 -0
  151. package/lib/types/src/dynamic-network/model/DynamicNetworkConfiguration.d.ts +16 -0
  152. package/lib/types/src/dynamic-network/model/DynamicNetworkConfiguration.d.ts.map +1 -0
  153. package/lib/types/src/index.d.ts +2 -0
  154. package/lib/types/src/index.d.ts.map +1 -1
  155. package/lib/types/src/pki/domain/DefaultPkiCertificateLoader.d.ts.map +1 -1
  156. package/lib/types/src/shared/model/ClearSignContext.d.ts +3 -0
  157. package/lib/types/src/shared/model/ClearSignContext.d.ts.map +1 -1
  158. package/lib/types/src/transaction/data/HttpProxyDataSource.d.ts +2 -1
  159. package/lib/types/src/transaction/data/HttpProxyDataSource.d.ts.map +1 -1
  160. package/lib/types/src/transaction/data/dto/ProxyDelegateCallDto.d.ts +1 -1
  161. package/lib/types/src/transaction/data/dto/ProxyDelegateCallDto.d.ts.map +1 -1
  162. package/lib/types/src/transaction/domain/TransactionContextLoader.d.ts +3 -1
  163. package/lib/types/src/transaction/domain/TransactionContextLoader.d.ts.map +1 -1
  164. package/lib/types/tsconfig.prod.tsbuildinfo +1 -1
  165. package/package.json +4 -4
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/trusted-name/data/HttpTrustedNameDataSource.ts"],
4
- "sourcesContent": ["import axios from \"axios\";\nimport { inject, injectable } from \"inversify\";\nimport { Either, Left, Right } from \"purify-ts\";\n\nimport { configTypes } from \"@/config/di/configTypes\";\nimport type { ContextModuleConfig } from \"@/config/model/ContextModuleConfig\";\nimport {\n LEDGER_CLIENT_VERSION_HEADER,\n LEDGER_ORIGIN_TOKEN_HEADER,\n} from \"@/shared/constant/HttpHeaders\";\nimport {\n GetDomainNameInfosParams,\n GetTrustedNameInfosParams,\n TrustedNameDataSource,\n} from \"@/trusted-name/data/TrustedNameDataSource\";\nimport PACKAGE from \"@root/package.json\";\n\nimport { TrustedNameDto } from \"./TrustedNameDto\";\n\n@injectable()\nexport class HttpTrustedNameDataSource implements TrustedNameDataSource {\n constructor(\n @inject(configTypes.Config) private readonly config: ContextModuleConfig,\n ) {}\n\n public async getDomainNamePayload({\n chainId,\n domain,\n challenge,\n }: GetDomainNameInfosParams): Promise<Either<Error, string>> {\n try {\n const type = \"eoa\"; // Externally owned account\n const source = \"ens\"; // Ethereum name service\n const response = await axios.request<TrustedNameDto>({\n method: \"GET\",\n url: `${this.config.metadataService.url}/names/ethereum/${chainId}/forward/${domain}?types=${type}&sources=${source}&challenge=${challenge}`,\n headers: {\n [LEDGER_CLIENT_VERSION_HEADER]: `context-module/${PACKAGE.version}`,\n [LEDGER_ORIGIN_TOKEN_HEADER]: this.config.originToken,\n },\n });\n\n return response.data.signedDescriptor?.data\n ? Right(response.data.signedDescriptor.data)\n : Left(\n new Error(\n \"[ContextModule] HttpTrustedNameDataSource: error getting domain payload\",\n ),\n );\n } catch (_error) {\n return Left(\n new Error(\n \"[ContextModule] HttpTrustedNameDataSource: Failed to fetch domain name\",\n ),\n );\n }\n }\n\n public async getTrustedNamePayload({\n chainId,\n address,\n challenge,\n sources,\n types,\n }: GetTrustedNameInfosParams): Promise<Either<Error, string>> {\n try {\n // TODO remove that filtering once https://ledgerhq.atlassian.net/browse/BACK-8075 is done\n // For now we have to filter or trusted names won't work with the generic parser, because transaction\n // fields descriptors can contain unsupported sources.\n sources = sources.filter(\n (source) => source === \"ens\" || source === \"crypto_asset_list\",\n );\n const response = await axios.request<TrustedNameDto>({\n method: \"GET\",\n url: `${this.config.metadataService.url}/names/ethereum/${chainId}/reverse/${address}?types=${types.join(\",\")}&sources=${sources.join(\",\")}&challenge=${challenge}`,\n headers: {\n [LEDGER_CLIENT_VERSION_HEADER]: `context-module/${PACKAGE.version}`,\n [LEDGER_ORIGIN_TOKEN_HEADER]: this.config.originToken,\n },\n });\n const trustedName = response.data;\n if (!trustedName?.signedDescriptor?.data) {\n return Left(\n new Error(\n `[ContextModule] HttpTrustedNameDataSource: no trusted name metadata for address ${address}`,\n ),\n );\n }\n const payload = trustedName.signedDescriptor.data;\n\n if (\n !trustedName.signedDescriptor.signatures ||\n typeof trustedName.signedDescriptor.signatures[this.config.cal.mode] !==\n \"string\"\n ) {\n // If we have no separated signature but a valid descriptor, it may mean the descriptor was\n // signed on-the-fly for dynamic sources such as ens\n return Right(payload);\n }\n\n const signature =\n trustedName.signedDescriptor.signatures[this.config.cal.mode]!;\n return Right(this.formatTrustedName(payload, signature));\n } catch (_error) {\n return Left(\n new Error(\n \"[ContextModule] HttpTrustedNameDataSource: Failed to fetch trusted name\",\n ),\n );\n }\n }\n\n private formatTrustedName(payload: string, signature: string): string {\n // Ensure correct padding\n if (signature.length % 2 !== 0) {\n signature = \"0\" + signature;\n }\n // TLV encoding as according to trusted name documentation\n const signatureTag = \"15\";\n const signatureLength = (signature.length / 2).toString(16);\n return `${payload}${signatureTag}${signatureLength}${signature}`;\n }\n}\n"],
5
- "mappings": "qtBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,+BAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAAkB,oBAClBC,EAAmC,qBACnCC,EAAoC,qBAEpCC,EAA4B,mCAE5BC,EAGO,yCAMPC,EAAoB,iCAKb,IAAMC,EAAN,KAAiE,CACtE,YAC+CC,EAC7C,CAD6C,YAAAA,CAC5C,CAEH,MAAa,qBAAqB,CAChC,QAAAC,EACA,OAAAC,EACA,UAAAC,CACF,EAA6D,CAC3D,GAAI,CAGF,MAAMC,EAAW,MAAM,EAAAC,QAAM,QAAwB,CACnD,OAAQ,MACR,IAAK,GAAG,KAAK,OAAO,gBAAgB,GAAG,mBAAmBJ,CAAO,YAAYC,CAAM,oCAA8CC,CAAS,GAC1I,QAAS,CACP,CAAC,8BAA4B,EAAG,kBAAkB,EAAAG,QAAQ,OAAO,GACjE,CAAC,4BAA0B,EAAG,KAAK,OAAO,WAC5C,CACF,CAAC,EAED,OA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E,EAC1D,MAAO,GAAGD,CAAO,GAAGE,CAAY,GAAGC,CAAe,GAAGF,CAAS,EAChE,CACF,EAtGad,EAANiB,EAAA,IADN,cAAW,EAGPC,EAAA,eAAO,cAAY,MAAM,IAFjBlB",
4
+ "sourcesContent": ["import axios from \"axios\";\nimport { inject, injectable } from \"inversify\";\nimport { Either, Left, Right } from \"purify-ts\";\n\nimport { configTypes } from \"@/config/di/configTypes\";\nimport type { ContextModuleConfig } from \"@/config/model/ContextModuleConfig\";\nimport {\n LEDGER_CLIENT_VERSION_HEADER,\n LEDGER_ORIGIN_TOKEN_HEADER,\n} from \"@/shared/constant/HttpHeaders\";\nimport {\n GetDomainNameInfosParams,\n GetTrustedNameInfosParams,\n TrustedNameDataSource,\n} from \"@/trusted-name/data/TrustedNameDataSource\";\nimport PACKAGE from \"@root/package.json\";\n\nimport { TrustedNameDto } from \"./TrustedNameDto\";\n\n@injectable()\nexport class HttpTrustedNameDataSource implements TrustedNameDataSource {\n constructor(\n @inject(configTypes.Config) private readonly config: ContextModuleConfig,\n ) {}\n\n public async getDomainNamePayload({\n chainId,\n domain,\n challenge,\n }: GetDomainNameInfosParams): Promise<Either<Error, string>> {\n try {\n const type = \"eoa\"; // Externally owned account\n const source = \"ens\"; // Ethereum name service\n const response = await axios.request<TrustedNameDto>({\n method: \"GET\",\n url: `${this.config.metadataServiceDomain.url}/v2/names/ethereum/${chainId}/forward/${domain}?types=${type}&sources=${source}&challenge=${challenge}`,\n headers: {\n [LEDGER_CLIENT_VERSION_HEADER]: `context-module/${PACKAGE.version}`,\n [LEDGER_ORIGIN_TOKEN_HEADER]: this.config.originToken,\n },\n });\n\n return response.data.signedDescriptor?.data\n ? Right(response.data.signedDescriptor.data)\n : Left(\n new Error(\n \"[ContextModule] HttpTrustedNameDataSource: error getting domain payload\",\n ),\n );\n } catch (_error) {\n return Left(\n new Error(\n \"[ContextModule] HttpTrustedNameDataSource: Failed to fetch domain name\",\n ),\n );\n }\n }\n\n public async getTrustedNamePayload({\n chainId,\n address,\n challenge,\n sources,\n types,\n }: GetTrustedNameInfosParams): Promise<Either<Error, string>> {\n try {\n // TODO remove that filtering once https://ledgerhq.atlassian.net/browse/BACK-8075 is done\n // For now we have to filter or trusted names won't work with the generic parser, because transaction\n // fields descriptors can contain unsupported sources.\n sources = sources.filter(\n (source) => source === \"ens\" || source === \"crypto_asset_list\",\n );\n const response = await axios.request<TrustedNameDto>({\n method: \"GET\",\n url: `${this.config.metadataServiceDomain.url}/v2/names/ethereum/${chainId}/reverse/${address}?types=${types.join(\",\")}&sources=${sources.join(\",\")}&challenge=${challenge}`,\n headers: {\n [LEDGER_CLIENT_VERSION_HEADER]: `context-module/${PACKAGE.version}`,\n [LEDGER_ORIGIN_TOKEN_HEADER]: this.config.originToken,\n },\n });\n const trustedName = response.data;\n if (!trustedName?.signedDescriptor?.data) {\n return Left(\n new Error(\n `[ContextModule] HttpTrustedNameDataSource: no trusted name metadata for address ${address}`,\n ),\n );\n }\n const payload = trustedName.signedDescriptor.data;\n\n if (\n !trustedName.signedDescriptor.signatures ||\n typeof trustedName.signedDescriptor.signatures[this.config.cal.mode] !==\n \"string\"\n ) {\n // If we have no separated signature but a valid descriptor, it may mean the descriptor was\n // signed on-the-fly for dynamic sources such as ens\n return Right(payload);\n }\n\n const signature =\n trustedName.signedDescriptor.signatures[this.config.cal.mode]!;\n return Right(this.formatTrustedName(payload, signature));\n } catch (_error) {\n return Left(\n new Error(\n \"[ContextModule] HttpTrustedNameDataSource: Failed to fetch trusted name\",\n ),\n );\n }\n }\n\n private formatTrustedName(payload: string, signature: string): string {\n // Ensure correct padding\n if (signature.length % 2 !== 0) {\n signature = \"0\" + signature;\n }\n // TLV encoding as according to trusted name documentation\n const signatureTag = \"15\";\n const signatureLength = (signature.length / 2).toString(16);\n return `${payload}${signatureTag}${signatureLength}${signature}`;\n }\n}\n"],
5
+ "mappings": "qtBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,+BAAAE,IAAA,eAAAC,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AAkB,KAClC,SAAO,QACL,IAAI,MACF,mFAAmFJ,CAAO,EAC5F,CACF,EAEF,MAAMK,EAAUD,EAAY,iBAAiB,KAE7C,GACE,CAACA,EAAY,iBAAiB,YAC9B,OAAOA,EAAY,iBAAiB,WAAW,KAAK,OAAO,IAAI,IAAI,GACjE,SAIF,SAAO,SAAMC,CAAO,EAGtB,MAAMC,EACJF,EAAY,iBAAiB,WAAW,KAAK,OAAO,IAAI,IAAI,EAC9D,SAAO,SAAM,KAAK,kBAAkBC,EAASC,CAAS,CAAC,CACzD,MAAiB,CACf,SAAO,QACL,IAAI,MACF,yEACF,CACF,CACF,CACF,CAEQ,kBAAkBD,EAAiBC,EAA2B,CAEhEA,EAAU,OAAS,IAAM,IAC3BA,EAAY,IAAMA,GAGpB,MAAMC,EAAe,KACfC,GAAmBF,EAAU,OAAS,GAAG,SAAS,EAAE,EAC1D,MAAO,GAAGD,CAAO,GAAGE,CAAY,GAAGC,CAAe,GAAGF,CAAS,EAChE,CACF,EAtGad,EAANiB,EAAA,IADN,cAAW,EAGPC,EAAA,eAAO,cAAY,MAAM,IAFjBlB",
6
6
  "names": ["HttpTrustedNameDataSource_exports", "__export", "HttpTrustedNameDataSource", "__toCommonJS", "import_axios", "import_inversify", "import_purify_ts", "import_configTypes", "import_HttpHeaders", "import_package", "HttpTrustedNameDataSource", "config", "chainId", "domain", "challenge", "response", "axios", "PACKAGE", "address", "sources", "types", "source", "trustedName", "payload", "signature", "signatureTag", "signatureLength", "__decorateClass", "__decorateParam"]
7
7
  }
@@ -1,2 +1,2 @@
1
- "use strict";var m=Object.create;var c=Object.defineProperty;var h=Object.getOwnPropertyDescriptor;var y=Object.getOwnPropertyNames;var g=Object.getPrototypeOf,v=Object.prototype.hasOwnProperty;var x=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of y(e))!v.call(a,n)&&n!==t&&c(a,n,{get:()=>e[n],enumerable:!(i=h(e,n))||i.enumerable});return a};var u=(a,e,t)=>(t=a!=null?m(g(a)):{},x(e||!a||!a.__esModule?c(t,"default",{value:a,enumerable:!0}):t,a));var o=u(require("axios")),r=require("purify-ts"),s=require("../../shared/constant/HttpHeaders"),p=require("../../trusted-name/data/HttpTrustedNameDataSource"),d=u(require("../../../package.json"));vi.mock("axios");const l={cal:{url:"https://crypto-assets-service.api.ledger.com/v1",mode:"prod",branch:"main"},metadataService:{url:"https://nft.api.live.ledger.com/v2"},originToken:"originToken"};describe("HttpTrustedNameDataSource",()=>{let a;beforeAll(()=>{a=new p.HttpTrustedNameDataSource(l),vi.clearAllMocks()}),describe("getDomainNamePayload",()=>{it("should call axios with the correct url and ledger client version header",async()=>{const e=`context-module/${d.default.version}`,t=vi.fn(()=>Promise.resolve({data:[]}));vi.spyOn(o.default,"request").mockImplementation(t),await a.getDomainNamePayload({chainId:137,challenge:"9876",domain:"hello.eth"}),expect(t).toHaveBeenCalledWith(expect.objectContaining({url:"https://nft.api.live.ledger.com/v2/names/ethereum/137/forward/hello.eth?types=eoa&sources=ens&challenge=9876",headers:{[s.LEDGER_CLIENT_VERSION_HEADER]:e,[s.LEDGER_ORIGIN_TOKEN_HEADER]:l.originToken}}))}),it("should throw an error when axios throws an error",async()=>{vi.spyOn(o.default,"request").mockRejectedValue(new Error);const e=await a.getDomainNamePayload({chainId:137,challenge:"",domain:"hello.eth"});expect(e).toEqual((0,r.Left)(new Error("[ContextModule] HttpTrustedNameDataSource: Failed to fetch domain name")))}),it("should return an error when no payload is returned",async()=>{const e={data:{test:""}};vi.spyOn(o.default,"request").mockResolvedValue(e);const t=await a.getDomainNamePayload({chainId:137,challenge:"",domain:"hello.eth"});expect(t).toEqual((0,r.Left)(new Error("[ContextModule] HttpTrustedNameDataSource: error getting domain payload")))}),it("should return a payload",async()=>{const e={data:{signedDescriptor:{data:"payload"}}};vi.spyOn(o.default,"request").mockResolvedValue(e);const t=await a.getDomainNamePayload({chainId:137,challenge:"challenge",domain:"hello.eth"});expect(t).toEqual((0,r.Right)("payload"))})}),describe("getTrustedNamePayload",()=>{it("should call axios with the correct url and ledger client version header",async()=>{const e=`context-module/${d.default.version}`,t=vi.fn(()=>Promise.resolve({data:[]}));vi.spyOn(o.default,"request").mockImplementation(t),await a.getTrustedNamePayload({chainId:137,address:"0x1234",challenge:"5678",sources:["ens","crypto_asset_list"],types:["eoa"]}),expect(t).toHaveBeenCalledWith(expect.objectContaining({url:"https://nft.api.live.ledger.com/v2/names/ethereum/137/reverse/0x1234?types=eoa&sources=ens,crypto_asset_list&challenge=5678",headers:{[s.LEDGER_CLIENT_VERSION_HEADER]:e,[s.LEDGER_ORIGIN_TOKEN_HEADER]:l.originToken}}))}),it("should throw an error when axios throws an error",async()=>{vi.spyOn(o.default,"request").mockRejectedValue(new Error);const e=await a.getTrustedNamePayload({chainId:137,address:"0x1234",challenge:"",sources:["ens"],types:["eoa"]});expect(e).toEqual((0,r.Left)(new Error("[ContextModule] HttpTrustedNameDataSource: Failed to fetch trusted name")))}),it("should return an error when no payload is returned",async()=>{const e={data:{test:""}};vi.spyOn(o.default,"request").mockResolvedValue(e);const t=await a.getTrustedNamePayload({chainId:137,address:"0x1234",challenge:"",sources:["ens"],types:["eoa"]});expect(t).toEqual((0,r.Left)(new Error("[ContextModule] HttpTrustedNameDataSource: no trusted name metadata for address 0x1234")))}),it("should return a payload",async()=>{const e={data:{signedDescriptor:{data:"payload"}}};vi.spyOn(o.default,"request").mockResolvedValue(e);const t=await a.getTrustedNamePayload({chainId:137,address:"0x1234",challenge:"",sources:["ens"],types:["eoa"]});expect(t).toEqual((0,r.Right)("payload"))}),it("should return a payload with a signature",async()=>{const e={data:{signedDescriptor:{data:"payload",signatures:{prod:"12345"}}}};vi.spyOn(o.default,"request").mockResolvedValue(e);const t=await a.getTrustedNamePayload({chainId:137,address:"0x1234",challenge:"",sources:["ens"],types:["eoa"]});expect(t).toEqual((0,r.Right)("payload153012345"))})})});
1
+ "use strict";var m=Object.create;var c=Object.defineProperty;var h=Object.getOwnPropertyDescriptor;var y=Object.getOwnPropertyNames;var g=Object.getPrototypeOf,v=Object.prototype.hasOwnProperty;var x=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of y(e))!v.call(a,n)&&n!==t&&c(a,n,{get:()=>e[n],enumerable:!(i=h(e,n))||i.enumerable});return a};var u=(a,e,t)=>(t=a!=null?m(g(a)):{},x(e||!a||!a.__esModule?c(t,"default",{value:a,enumerable:!0}):t,a));var o=u(require("axios")),r=require("purify-ts"),s=require("../../shared/constant/HttpHeaders"),p=require("../../trusted-name/data/HttpTrustedNameDataSource"),d=u(require("../../../package.json"));vi.mock("axios");const l={cal:{url:"https://crypto-assets-service.api.ledger.com/v1",mode:"prod",branch:"main"},metadataServiceDomain:{url:"https://nft.api.live.ledger.com"},originToken:"originToken"};describe("HttpTrustedNameDataSource",()=>{let a;beforeAll(()=>{a=new p.HttpTrustedNameDataSource(l),vi.clearAllMocks()}),describe("getDomainNamePayload",()=>{it("should call axios with the correct url and ledger client version header",async()=>{const e=`context-module/${d.default.version}`,t=vi.fn(()=>Promise.resolve({data:[]}));vi.spyOn(o.default,"request").mockImplementation(t),await a.getDomainNamePayload({chainId:137,challenge:"9876",domain:"hello.eth"}),expect(t).toHaveBeenCalledWith(expect.objectContaining({url:"https://nft.api.live.ledger.com/v2/names/ethereum/137/forward/hello.eth?types=eoa&sources=ens&challenge=9876",headers:{[s.LEDGER_CLIENT_VERSION_HEADER]:e,[s.LEDGER_ORIGIN_TOKEN_HEADER]:l.originToken}}))}),it("should throw an error when axios throws an error",async()=>{vi.spyOn(o.default,"request").mockRejectedValue(new Error);const e=await a.getDomainNamePayload({chainId:137,challenge:"",domain:"hello.eth"});expect(e).toEqual((0,r.Left)(new Error("[ContextModule] HttpTrustedNameDataSource: Failed to fetch domain name")))}),it("should return an error when no payload is returned",async()=>{const e={data:{test:""}};vi.spyOn(o.default,"request").mockResolvedValue(e);const t=await a.getDomainNamePayload({chainId:137,challenge:"",domain:"hello.eth"});expect(t).toEqual((0,r.Left)(new Error("[ContextModule] HttpTrustedNameDataSource: error getting domain payload")))}),it("should return a payload",async()=>{const e={data:{signedDescriptor:{data:"payload"}}};vi.spyOn(o.default,"request").mockResolvedValue(e);const t=await a.getDomainNamePayload({chainId:137,challenge:"challenge",domain:"hello.eth"});expect(t).toEqual((0,r.Right)("payload"))})}),describe("getTrustedNamePayload",()=>{it("should call axios with the correct url and ledger client version header",async()=>{const e=`context-module/${d.default.version}`,t=vi.fn(()=>Promise.resolve({data:[]}));vi.spyOn(o.default,"request").mockImplementation(t),await a.getTrustedNamePayload({chainId:137,address:"0x1234",challenge:"5678",sources:["ens","crypto_asset_list"],types:["eoa"]}),expect(t).toHaveBeenCalledWith(expect.objectContaining({url:"https://nft.api.live.ledger.com/v2/names/ethereum/137/reverse/0x1234?types=eoa&sources=ens,crypto_asset_list&challenge=5678",headers:{[s.LEDGER_CLIENT_VERSION_HEADER]:e,[s.LEDGER_ORIGIN_TOKEN_HEADER]:l.originToken}}))}),it("should throw an error when axios throws an error",async()=>{vi.spyOn(o.default,"request").mockRejectedValue(new Error);const e=await a.getTrustedNamePayload({chainId:137,address:"0x1234",challenge:"",sources:["ens"],types:["eoa"]});expect(e).toEqual((0,r.Left)(new Error("[ContextModule] HttpTrustedNameDataSource: Failed to fetch trusted name")))}),it("should return an error when no payload is returned",async()=>{const e={data:{test:""}};vi.spyOn(o.default,"request").mockResolvedValue(e);const t=await a.getTrustedNamePayload({chainId:137,address:"0x1234",challenge:"",sources:["ens"],types:["eoa"]});expect(t).toEqual((0,r.Left)(new Error("[ContextModule] HttpTrustedNameDataSource: no trusted name metadata for address 0x1234")))}),it("should return a payload",async()=>{const e={data:{signedDescriptor:{data:"payload"}}};vi.spyOn(o.default,"request").mockResolvedValue(e);const t=await a.getTrustedNamePayload({chainId:137,address:"0x1234",challenge:"",sources:["ens"],types:["eoa"]});expect(t).toEqual((0,r.Right)("payload"))}),it("should return a payload with a signature",async()=>{const e={data:{signedDescriptor:{data:"payload",signatures:{prod:"12345"}}}};vi.spyOn(o.default,"request").mockResolvedValue(e);const t=await a.getTrustedNamePayload({chainId:137,address:"0x1234",challenge:"",sources:["ens"],types:["eoa"]});expect(t).toEqual((0,r.Right)("payload153012345"))})})});
2
2
  //# sourceMappingURL=HttpTrustedNameDataSource.test.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/trusted-name/data/HttpTrustedNameDataSource.test.ts"],
4
- "sourcesContent": ["import axios from \"axios\";\nimport { Left, Right } from \"purify-ts\";\n\nimport { type ContextModuleConfig } from \"@/config/model/ContextModuleConfig\";\nimport {\n LEDGER_CLIENT_VERSION_HEADER,\n LEDGER_ORIGIN_TOKEN_HEADER,\n} from \"@/shared/constant/HttpHeaders\";\nimport { HttpTrustedNameDataSource } from \"@/trusted-name/data/HttpTrustedNameDataSource\";\nimport { type TrustedNameDataSource } from \"@/trusted-name/data/TrustedNameDataSource\";\nimport PACKAGE from \"@root/package.json\";\n\nvi.mock(\"axios\");\n\nconst config = {\n cal: {\n url: \"https://crypto-assets-service.api.ledger.com/v1\",\n mode: \"prod\",\n branch: \"main\",\n },\n metadataService: {\n url: \"https://nft.api.live.ledger.com/v2\",\n },\n originToken: \"originToken\",\n} as ContextModuleConfig;\ndescribe(\"HttpTrustedNameDataSource\", () => {\n let datasource: TrustedNameDataSource;\n\n beforeAll(() => {\n datasource = new HttpTrustedNameDataSource(config);\n vi.clearAllMocks();\n });\n\n describe(\"getDomainNamePayload\", () => {\n it(\"should call axios with the correct url and ledger client version header\", async () => {\n // GIVEN\n const version = `context-module/${PACKAGE.version}`;\n const requestSpy = vi.fn(() => Promise.resolve({ data: [] }));\n vi.spyOn(axios, \"request\").mockImplementation(requestSpy);\n\n // WHEN\n await datasource.getDomainNamePayload({\n chainId: 137,\n challenge: \"9876\",\n domain: \"hello.eth\",\n });\n\n // THEN\n expect(requestSpy).toHaveBeenCalledWith(\n expect.objectContaining({\n url: `https://nft.api.live.ledger.com/v2/names/ethereum/137/forward/hello.eth?types=eoa&sources=ens&challenge=9876`,\n headers: {\n [LEDGER_CLIENT_VERSION_HEADER]: version,\n [LEDGER_ORIGIN_TOKEN_HEADER]: config.originToken,\n },\n }),\n );\n });\n\n it(\"should throw an error when axios throws an error\", async () => {\n // GIVEN\n vi.spyOn(axios, \"request\").mockRejectedValue(new Error());\n\n // WHEN\n const result = await datasource.getDomainNamePayload({\n chainId: 137,\n challenge: \"\",\n domain: \"hello.eth\",\n });\n\n // THEN\n expect(result).toEqual(\n Left(\n new Error(\n \"[ContextModule] HttpTrustedNameDataSource: Failed to fetch domain name\",\n ),\n ),\n );\n });\n\n it(\"should return an error when no payload is returned\", async () => {\n // GIVEN\n const response = { data: { test: \"\" } };\n vi.spyOn(axios, \"request\").mockResolvedValue(response);\n\n // WHEN\n const result = await datasource.getDomainNamePayload({\n chainId: 137,\n challenge: \"\",\n domain: \"hello.eth\",\n });\n\n // THEN\n expect(result).toEqual(\n Left(\n new Error(\n \"[ContextModule] HttpTrustedNameDataSource: error getting domain payload\",\n ),\n ),\n );\n });\n\n it(\"should return a payload\", async () => {\n // GIVEN\n const response = { data: { signedDescriptor: { data: \"payload\" } } };\n vi.spyOn(axios, \"request\").mockResolvedValue(response);\n\n // WHEN\n const result = await datasource.getDomainNamePayload({\n chainId: 137,\n challenge: \"challenge\",\n domain: \"hello.eth\",\n });\n\n // THEN\n expect(result).toEqual(Right(\"payload\"));\n });\n });\n\n describe(\"getTrustedNamePayload\", () => {\n it(\"should call axios with the correct url and ledger client version header\", async () => {\n // GIVEN\n const version = `context-module/${PACKAGE.version}`;\n const requestSpy = vi.fn(() => Promise.resolve({ data: [] }));\n vi.spyOn(axios, \"request\").mockImplementation(requestSpy);\n\n // WHEN\n await datasource.getTrustedNamePayload({\n chainId: 137,\n address: \"0x1234\",\n challenge: \"5678\",\n sources: [\"ens\", \"crypto_asset_list\"],\n types: [\"eoa\"],\n });\n\n // THEN\n expect(requestSpy).toHaveBeenCalledWith(\n expect.objectContaining({\n url: `https://nft.api.live.ledger.com/v2/names/ethereum/137/reverse/0x1234?types=eoa&sources=ens,crypto_asset_list&challenge=5678`,\n headers: {\n [LEDGER_CLIENT_VERSION_HEADER]: version,\n [LEDGER_ORIGIN_TOKEN_HEADER]: config.originToken,\n },\n }),\n );\n });\n\n it(\"should throw an error when axios throws an error\", async () => {\n // GIVEN\n vi.spyOn(axios, \"request\").mockRejectedValue(new Error());\n\n // WHEN\n const result = await datasource.getTrustedNamePayload({\n chainId: 137,\n address: \"0x1234\",\n challenge: \"\",\n sources: [\"ens\"],\n types: [\"eoa\"],\n });\n\n // THEN\n expect(result).toEqual(\n Left(\n new Error(\n \"[ContextModule] HttpTrustedNameDataSource: Failed to fetch trusted name\",\n ),\n ),\n );\n });\n\n it(\"should return an error when no payload is returned\", async () => {\n // GIVEN\n const response = { data: { test: \"\" } };\n vi.spyOn(axios, \"request\").mockResolvedValue(response);\n\n // WHEN\n const result = await datasource.getTrustedNamePayload({\n chainId: 137,\n address: \"0x1234\",\n challenge: \"\",\n sources: [\"ens\"],\n types: [\"eoa\"],\n });\n\n // THEN\n expect(result).toEqual(\n Left(\n new Error(\n \"[ContextModule] HttpTrustedNameDataSource: no trusted name metadata for address 0x1234\",\n ),\n ),\n );\n });\n\n it(\"should return a payload\", async () => {\n // GIVEN\n const response = {\n data: {\n signedDescriptor: { data: \"payload\" },\n },\n };\n vi.spyOn(axios, \"request\").mockResolvedValue(response);\n\n // WHEN\n const result = await datasource.getTrustedNamePayload({\n chainId: 137,\n address: \"0x1234\",\n challenge: \"\",\n sources: [\"ens\"],\n types: [\"eoa\"],\n });\n\n // THEN\n expect(result).toEqual(Right(\"payload\"));\n });\n\n it(\"should return a payload with a signature\", async () => {\n // GIVEN\n const response = {\n data: {\n signedDescriptor: { data: \"payload\", signatures: { prod: \"12345\" } },\n },\n };\n vi.spyOn(axios, \"request\").mockResolvedValue(response);\n\n // WHEN\n const result = await datasource.getTrustedNamePayload({\n chainId: 137,\n address: \"0x1234\",\n challenge: \"\",\n sources: [\"ens\"],\n types: [\"eoa\"],\n });\n\n // THEN\n expect(result).toEqual(Right(\"payload153012345\"));\n });\n });\n});\n"],
5
- "mappings": "wdAAA,IAAAA,EAAkB,oBAClBC,EAA4B,qBAG5BC,EAGO,yCACPC,EAA0C,yDAE1CC,EAAoB,iCAEpB,GAAG,KAAK,OAAO,EAEf,MAAMC,EAAS,CACb,IAAK,CACH,IAAK,kDACL,KAAM,OACN,OAAQ,MACV,EACA,gBAAiB,CACf,IAAK,oCACP,EACA,YAAa,aACf,EACA,SAAS,4BAA6B,IAAM,CAC1C,IAAIC,EAEJ,UAAU,IAAM,CACdA,EAAa,IAAI,4BAA0BD,CAAM,EACjD,GAAG,cAAc,CACnB,CAAC,EAED,SAAS,uBAAwB,IAAM,CACrC,GAAG,0EAA2E,SAAY,CAExF,MAAME,EAAU,kBAAkB,EAAAC,QAAQ,OAAO,GAC3CC,EAAa,GAAG,GAAG,IAAM,QAAQ,QAAQ,CAAE,KAAM,CAAC,CAAE,CAAC,CAAC,EAC5D,GAAG,MAAM,EAAAC,QAAO,SAAS,EAAE,mBAAmBD,CAAU,EAGxD,MAAMH,EAAW,qBAAqB,CACpC,QAAS,IACT,UAAW,OACX,OAAQ,WACV,CAAC,EAGD,OAAOG,CAAU,EAAE,qBACjB,OAAO,iBAAiB,CACtB,IAAK,+GACL,QAAS,CACP,CAAC,8BAA4B,EAAGF,EAChC,CAAC,4BAA0B,EAAGF,EAAO,WACvC,CACF,CAAC,CACH,CACF,CAAC,EAED,GAAG,mDAAoD,SAAY,CAEjE,GAAG,MAAM,EAAAK,QAAO,SAAS,EAAE,kBAAkB,IAAI,KAAO,EAGxD,MAAMC,EAAS,MAAML,EAAW,qBAAqB,CACnD,QAAS,IACT,UAAW,GACX,OAAQ,WACV,CAAC,EAGD,OAAOK,CAAM,EAAE,WACb,QACE,IAAI,MACF,wEACF,CACF,CACF,CACF,CAAC,EAED,GAAG,qDAAsD,SAAY,CAEn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,WAAQ,SAAM,kBAAkB,CAAC,CAClD,CAAC,CACH,CAAC,CACH,CAAC",
4
+ "sourcesContent": ["import axios from \"axios\";\nimport { Left, Right } from \"purify-ts\";\n\nimport { type ContextModuleConfig } from \"@/config/model/ContextModuleConfig\";\nimport {\n LEDGER_CLIENT_VERSION_HEADER,\n LEDGER_ORIGIN_TOKEN_HEADER,\n} from \"@/shared/constant/HttpHeaders\";\nimport { HttpTrustedNameDataSource } from \"@/trusted-name/data/HttpTrustedNameDataSource\";\nimport { type TrustedNameDataSource } from \"@/trusted-name/data/TrustedNameDataSource\";\nimport PACKAGE from \"@root/package.json\";\n\nvi.mock(\"axios\");\n\nconst config = {\n cal: {\n url: \"https://crypto-assets-service.api.ledger.com/v1\",\n mode: \"prod\",\n branch: \"main\",\n },\n metadataServiceDomain: {\n url: \"https://nft.api.live.ledger.com\",\n },\n originToken: \"originToken\",\n} as ContextModuleConfig;\ndescribe(\"HttpTrustedNameDataSource\", () => {\n let datasource: TrustedNameDataSource;\n\n beforeAll(() => {\n datasource = new HttpTrustedNameDataSource(config);\n vi.clearAllMocks();\n });\n\n describe(\"getDomainNamePayload\", () => {\n it(\"should call axios with the correct url and ledger client version header\", async () => {\n // GIVEN\n const version = `context-module/${PACKAGE.version}`;\n const requestSpy = vi.fn(() => Promise.resolve({ data: [] }));\n vi.spyOn(axios, \"request\").mockImplementation(requestSpy);\n\n // WHEN\n await datasource.getDomainNamePayload({\n chainId: 137,\n challenge: \"9876\",\n domain: \"hello.eth\",\n });\n\n // THEN\n expect(requestSpy).toHaveBeenCalledWith(\n expect.objectContaining({\n url: `https://nft.api.live.ledger.com/v2/names/ethereum/137/forward/hello.eth?types=eoa&sources=ens&challenge=9876`,\n headers: {\n [LEDGER_CLIENT_VERSION_HEADER]: version,\n [LEDGER_ORIGIN_TOKEN_HEADER]: config.originToken,\n },\n }),\n );\n });\n\n it(\"should throw an error when axios throws an error\", async () => {\n // GIVEN\n vi.spyOn(axios, \"request\").mockRejectedValue(new Error());\n\n // WHEN\n const result = await datasource.getDomainNamePayload({\n chainId: 137,\n challenge: \"\",\n domain: \"hello.eth\",\n });\n\n // THEN\n expect(result).toEqual(\n Left(\n new Error(\n \"[ContextModule] HttpTrustedNameDataSource: Failed to fetch domain name\",\n ),\n ),\n );\n });\n\n it(\"should return an error when no payload is returned\", async () => {\n // GIVEN\n const response = { data: { test: \"\" } };\n vi.spyOn(axios, \"request\").mockResolvedValue(response);\n\n // WHEN\n const result = await datasource.getDomainNamePayload({\n chainId: 137,\n challenge: \"\",\n domain: \"hello.eth\",\n });\n\n // THEN\n expect(result).toEqual(\n Left(\n new Error(\n \"[ContextModule] HttpTrustedNameDataSource: error getting domain payload\",\n ),\n ),\n );\n });\n\n it(\"should return a payload\", async () => {\n // GIVEN\n const response = { data: { signedDescriptor: { data: \"payload\" } } };\n vi.spyOn(axios, \"request\").mockResolvedValue(response);\n\n // WHEN\n const result = await datasource.getDomainNamePayload({\n chainId: 137,\n challenge: \"challenge\",\n domain: \"hello.eth\",\n });\n\n // THEN\n expect(result).toEqual(Right(\"payload\"));\n });\n });\n\n describe(\"getTrustedNamePayload\", () => {\n it(\"should call axios with the correct url and ledger client version header\", async () => {\n // GIVEN\n const version = `context-module/${PACKAGE.version}`;\n const requestSpy = vi.fn(() => Promise.resolve({ data: [] }));\n vi.spyOn(axios, \"request\").mockImplementation(requestSpy);\n\n // WHEN\n await datasource.getTrustedNamePayload({\n chainId: 137,\n address: \"0x1234\",\n challenge: \"5678\",\n sources: [\"ens\", \"crypto_asset_list\"],\n types: [\"eoa\"],\n });\n\n // THEN\n expect(requestSpy).toHaveBeenCalledWith(\n expect.objectContaining({\n url: `https://nft.api.live.ledger.com/v2/names/ethereum/137/reverse/0x1234?types=eoa&sources=ens,crypto_asset_list&challenge=5678`,\n headers: {\n [LEDGER_CLIENT_VERSION_HEADER]: version,\n [LEDGER_ORIGIN_TOKEN_HEADER]: config.originToken,\n },\n }),\n );\n });\n\n it(\"should throw an error when axios throws an error\", async () => {\n // GIVEN\n vi.spyOn(axios, \"request\").mockRejectedValue(new Error());\n\n // WHEN\n const result = await datasource.getTrustedNamePayload({\n chainId: 137,\n address: \"0x1234\",\n challenge: \"\",\n sources: [\"ens\"],\n types: [\"eoa\"],\n });\n\n // THEN\n expect(result).toEqual(\n Left(\n new Error(\n \"[ContextModule] HttpTrustedNameDataSource: Failed to fetch trusted name\",\n ),\n ),\n );\n });\n\n it(\"should return an error when no payload is returned\", async () => {\n // GIVEN\n const response = { data: { test: \"\" } };\n vi.spyOn(axios, \"request\").mockResolvedValue(response);\n\n // WHEN\n const result = await datasource.getTrustedNamePayload({\n chainId: 137,\n address: \"0x1234\",\n challenge: \"\",\n sources: [\"ens\"],\n types: [\"eoa\"],\n });\n\n // THEN\n expect(result).toEqual(\n Left(\n new Error(\n \"[ContextModule] HttpTrustedNameDataSource: no trusted name metadata for address 0x1234\",\n ),\n ),\n );\n });\n\n it(\"should return a payload\", async () => {\n // GIVEN\n const response = {\n data: {\n signedDescriptor: { data: \"payload\" },\n },\n };\n vi.spyOn(axios, \"request\").mockResolvedValue(response);\n\n // WHEN\n const result = await datasource.getTrustedNamePayload({\n chainId: 137,\n address: \"0x1234\",\n challenge: \"\",\n sources: [\"ens\"],\n types: [\"eoa\"],\n });\n\n // THEN\n expect(result).toEqual(Right(\"payload\"));\n });\n\n it(\"should return a payload with a signature\", async () => {\n // GIVEN\n const response = {\n data: {\n signedDescriptor: { data: \"payload\", signatures: { prod: \"12345\" } },\n },\n };\n vi.spyOn(axios, \"request\").mockResolvedValue(response);\n\n // WHEN\n const result = await datasource.getTrustedNamePayload({\n chainId: 137,\n address: \"0x1234\",\n challenge: \"\",\n sources: [\"ens\"],\n types: [\"eoa\"],\n });\n\n // THEN\n expect(result).toEqual(Right(\"payload153012345\"));\n });\n });\n});\n"],
5
+ "mappings": "wdAAA,IAAAA,EAAkB,oBAClBC,EAA4B,qBAG5BC,EAGO,yCACPC,EAA0C,yDAE1CC,EAAoB,iCAEpB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,CAEnE,MAAMC,EAAW,CAAE,KAAM,CAAE,KAAM,EAAG,CAAE,EACtC,GAAG,MAAM,EAAAF,QAAO,SAAS,EAAE,kBAAkBE,CAAQ,EAGrD,MAAMD,EAAS,MAAML,EAAW,sBAAsB,CACpD,QAAS,IACT,QAAS,SACT,UAAW,GACX,QAAS,CAAC,KAAK,EACf,MAAO,CAAC,KAAK,CACf,CAAC,EAGD,OAAOK,CAAM,EAAE,WACb,QACE,IAAI,MACF,wFACF,CACF,CACF,CACF,CAAC,EAED,GAAG,0BAA2B,SAAY,CAExC,MAAMC,EAAW,CACf,KAAM,CACJ,iBAAkB,CAAE,KAAM,SAAU,CACtC,CACF,EACA,GAAG,MAAM,EAAAF,QAAO,SAAS,EAAE,kBAAkBE,CAAQ,EAGrD,MAAMD,EAAS,MAAML,EAAW,sBAAsB,CACpD,QAAS,IACT,QAAS,SACT,UAAW,GACX,QAAS,CAAC,KAAK,EACf,MAAO,CAAC,KAAK,CACf,CAAC,EAGD,OAAOK,CAAM,EAAE,WAAQ,SAAM,SAAS,CAAC,CACzC,CAAC,EAED,GAAG,2CAA4C,SAAY,CAEzD,MAAMC,EAAW,CACf,KAAM,CACJ,iBAAkB,CAAE,KAAM,UAAW,WAAY,CAAE,KAAM,OAAQ,CAAE,CACrE,CACF,EACA,GAAG,MAAM,EAAAF,QAAO,SAAS,EAAE,kBAAkBE,CAAQ,EAGrD,MAAMD,EAAS,MAAML,EAAW,sBAAsB,CACpD,QAAS,IACT,QAAS,SACT,UAAW,GACX,QAAS,CAAC,KAAK,EACf,MAAO,CAAC,KAAK,CACf,CAAC,EAGD,OAAOK,CAAM,EAAE,WAAQ,SAAM,kBAAkB,CAAC,CAClD,CAAC,CACH,CAAC,CACH,CAAC",
6
6
  "names": ["import_axios", "import_purify_ts", "import_HttpHeaders", "import_HttpTrustedNameDataSource", "import_package", "config", "datasource", "version", "PACKAGE", "requestSpy", "axios", "result", "response"]
7
7
  }
@@ -1,2 +1,2 @@
1
- "use strict";var l=require("purify-ts"),t=require("../../shared/model/ClearSignContext"),n=require("../../trusted-name/domain/TrustedNameContextLoader");describe("TrustedNameContextLoader",()=>{const o={getDomainNamePayload:vi.fn(),getTrustedNamePayload:vi.fn()};beforeEach(()=>{vi.restoreAllMocks(),vi.spyOn(o,"getDomainNamePayload").mockResolvedValue((0,l.Right)("payload"))}),describe("load function",async()=>{it("should return an empty array when no domain or registry",async()=>{const e={},r=new n.TrustedNameContextLoader(o),a=()=>r.load(e);await expect(a()).resolves.toEqual([])}),it("should return an error when domain > max length",async()=>{const e={domain:"maxlength-maxlength-maxlength-maxlength-maxlength-maxlength",challenge:"challenge"},a=await new n.TrustedNameContextLoader(o).load(e);expect(a).toEqual([{type:t.ClearSignContextType.ERROR,error:new Error("[ContextModule] TrustedNameLoader: invalid domain")}])}),it("should return an error when domain is not valid",async()=>{const e={domain:"hello\u{1F44B}",challenge:"challenge"},a=await new n.TrustedNameContextLoader(o).load(e);expect(a).toEqual([{type:t.ClearSignContextType.ERROR,error:new Error("[ContextModule] TrustedNameLoader: invalid domain")}])}),it("should return a payload",async()=>{const e={domain:"hello.eth",challenge:"challenge"},a=await new n.TrustedNameContextLoader(o).load(e);expect(a).toEqual([{type:t.ClearSignContextType.TRUSTED_NAME,payload:"payload"}])}),it("should return an error when unable to fetch the datasource",async()=>{const e={domain:"hello.eth",challenge:"challenge"};vi.spyOn(o,"getDomainNamePayload").mockResolvedValue((0,l.Left)(new Error("error")));const a=await new n.TrustedNameContextLoader(o).load(e);expect(a).toEqual([{type:t.ClearSignContextType.ERROR,error:new Error("error")}])}),it("should return an empty array when no challenge",async()=>{const e={domain:"hello.eth",challenge:void 0},a=await new n.TrustedNameContextLoader(o).load(e);expect(a).toEqual([])})}),describe("loadField function",()=>{it("should return an error when field type if not supported",async()=>{const e={type:t.ClearSignContextType.TOKEN,chainId:7,address:"0x1234"},a=await new n.TrustedNameContextLoader(o).loadField(e);expect(a).toEqual(null)}),it("should return a payload",async()=>{const e={type:t.ClearSignContextType.TRUSTED_NAME,chainId:7,address:"0x1234",challenge:"17",sources:["ens"],types:["eoa"]};vi.spyOn(o,"getTrustedNamePayload").mockResolvedValue((0,l.Right)("payload"));const a=await new n.TrustedNameContextLoader(o).loadField(e);expect(a).toEqual({type:t.ClearSignContextType.TRUSTED_NAME,payload:"payload"})}),it("should return an error when unable to fetch the datasource",async()=>{const e={type:t.ClearSignContextType.TRUSTED_NAME,chainId:7,address:"0x1234",challenge:"17",sources:["ens"],types:["eoa"]};vi.spyOn(o,"getTrustedNamePayload").mockResolvedValue((0,l.Left)(new Error("error")));const a=await new n.TrustedNameContextLoader(o).loadField(e);expect(a).toEqual({type:t.ClearSignContextType.ERROR,error:new Error("error")})})})});
1
+ "use strict";var l=require("purify-ts"),t=require("../../shared/model/ClearSignContext"),n=require("../../trusted-name/domain/TrustedNameContextLoader");describe("TrustedNameContextLoader",()=>{const o={getDomainNamePayload:vi.fn(),getTrustedNamePayload:vi.fn()};beforeEach(()=>{vi.restoreAllMocks(),vi.spyOn(o,"getDomainNamePayload").mockResolvedValue((0,l.Right)("payload"))}),describe("load function",()=>{it("should return an empty array when no domain or registry",async()=>{const e={},r=new n.TrustedNameContextLoader(o),a=()=>r.load(e);await expect(a()).resolves.toEqual([])}),it("should return an error when domain > max length",async()=>{const e={domain:"maxlength-maxlength-maxlength-maxlength-maxlength-maxlength",challenge:"challenge"},a=await new n.TrustedNameContextLoader(o).load(e);expect(a).toEqual([{type:t.ClearSignContextType.ERROR,error:new Error("[ContextModule] TrustedNameLoader: invalid domain")}])}),it("should return an error when domain is not valid",async()=>{const e={domain:"hello\u{1F44B}",challenge:"challenge"},a=await new n.TrustedNameContextLoader(o).load(e);expect(a).toEqual([{type:t.ClearSignContextType.ERROR,error:new Error("[ContextModule] TrustedNameLoader: invalid domain")}])}),it("should return a payload",async()=>{const e={domain:"hello.eth",challenge:"challenge"},a=await new n.TrustedNameContextLoader(o).load(e);expect(a).toEqual([{type:t.ClearSignContextType.TRUSTED_NAME,payload:"payload"}])}),it("should return an error when unable to fetch the datasource",async()=>{const e={domain:"hello.eth",challenge:"challenge"};vi.spyOn(o,"getDomainNamePayload").mockResolvedValue((0,l.Left)(new Error("error")));const a=await new n.TrustedNameContextLoader(o).load(e);expect(a).toEqual([{type:t.ClearSignContextType.ERROR,error:new Error("error")}])}),it("should return an empty array when no challenge",async()=>{const e={domain:"hello.eth",challenge:void 0},a=await new n.TrustedNameContextLoader(o).load(e);expect(a).toEqual([])})}),describe("loadField function",()=>{it("should return an error when field type if not supported",async()=>{const e={type:t.ClearSignContextType.TOKEN,chainId:7,address:"0x1234"},a=await new n.TrustedNameContextLoader(o).loadField(e);expect(a).toEqual(null)}),it("should return a payload",async()=>{const e={type:t.ClearSignContextType.TRUSTED_NAME,chainId:7,address:"0x1234",challenge:"17",sources:["ens"],types:["eoa"]};vi.spyOn(o,"getTrustedNamePayload").mockResolvedValue((0,l.Right)("payload"));const a=await new n.TrustedNameContextLoader(o).loadField(e);expect(a).toEqual({type:t.ClearSignContextType.TRUSTED_NAME,payload:"payload"})}),it("should return an error when unable to fetch the datasource",async()=>{const e={type:t.ClearSignContextType.TRUSTED_NAME,chainId:7,address:"0x1234",challenge:"17",sources:["ens"],types:["eoa"]};vi.spyOn(o,"getTrustedNamePayload").mockResolvedValue((0,l.Left)(new Error("error")));const a=await new n.TrustedNameContextLoader(o).loadField(e);expect(a).toEqual({type:t.ClearSignContextType.ERROR,error:new Error("error")})})})});
2
2
  //# sourceMappingURL=TrustedNameContextLoader.test.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/trusted-name/domain/TrustedNameContextLoader.test.ts"],
4
- "sourcesContent": ["import { Left, Right } from \"purify-ts\";\n\nimport { ClearSignContextType } from \"@/shared/model/ClearSignContext\";\nimport {\n type TransactionContext,\n type TransactionFieldContext,\n} from \"@/shared/model/TransactionContext\";\nimport { type TrustedNameDataSource } from \"@/trusted-name/data/TrustedNameDataSource\";\nimport { TrustedNameContextLoader } from \"@/trusted-name/domain/TrustedNameContextLoader\";\n\ndescribe(\"TrustedNameContextLoader\", () => {\n const mockTrustedNameDataSource: TrustedNameDataSource = {\n getDomainNamePayload: vi.fn(),\n getTrustedNamePayload: vi.fn(),\n };\n\n beforeEach(() => {\n vi.restoreAllMocks();\n vi.spyOn(\n mockTrustedNameDataSource,\n \"getDomainNamePayload\",\n ).mockResolvedValue(Right(\"payload\"));\n });\n\n describe(\"load function\", async () => {\n it(\"should return an empty array when no domain or registry\", async () => {\n const transaction = {} as TransactionContext;\n const loader = new TrustedNameContextLoader(mockTrustedNameDataSource);\n const promise = () => loader.load(transaction);\n\n await expect(promise()).resolves.toEqual([]);\n });\n\n it(\"should return an error when domain > max length\", async () => {\n const transaction = {\n domain: \"maxlength-maxlength-maxlength-maxlength-maxlength-maxlength\",\n challenge: \"challenge\",\n } as TransactionContext;\n\n const loader = new TrustedNameContextLoader(mockTrustedNameDataSource);\n const result = await loader.load(transaction);\n\n expect(result).toEqual([\n {\n type: ClearSignContextType.ERROR,\n error: new Error(\"[ContextModule] TrustedNameLoader: invalid domain\"),\n },\n ]);\n });\n\n it(\"should return an error when domain is not valid\", async () => {\n const transaction = {\n domain: \"hello\uD83D\uDC4B\",\n challenge: \"challenge\",\n } as TransactionContext;\n\n const loader = new TrustedNameContextLoader(mockTrustedNameDataSource);\n const result = await loader.load(transaction);\n\n expect(result).toEqual([\n {\n type: ClearSignContextType.ERROR,\n error: new Error(\"[ContextModule] TrustedNameLoader: invalid domain\"),\n },\n ]);\n });\n\n it(\"should return a payload\", async () => {\n const transaction = {\n domain: \"hello.eth\",\n challenge: \"challenge\",\n } as TransactionContext;\n\n const loader = new TrustedNameContextLoader(mockTrustedNameDataSource);\n const result = await loader.load(transaction);\n\n expect(result).toEqual([\n {\n type: ClearSignContextType.TRUSTED_NAME,\n payload: \"payload\",\n },\n ]);\n });\n\n it(\"should return an error when unable to fetch the datasource\", async () => {\n // GIVEN\n const transaction = {\n domain: \"hello.eth\",\n challenge: \"challenge\",\n } as TransactionContext;\n\n // WHEN\n vi.spyOn(\n mockTrustedNameDataSource,\n \"getDomainNamePayload\",\n ).mockResolvedValue(Left(new Error(\"error\")));\n const loader = new TrustedNameContextLoader(mockTrustedNameDataSource);\n const result = await loader.load(transaction);\n\n // THEN\n expect(result).toEqual([\n { type: ClearSignContextType.ERROR, error: new Error(\"error\") },\n ]);\n });\n\n it(\"should return an empty array when no challenge\", async () => {\n // GIVEN\n const transaction = {\n domain: \"hello.eth\",\n challenge: undefined,\n } as TransactionContext;\n\n // WHEN\n const loader = new TrustedNameContextLoader(mockTrustedNameDataSource);\n const result = await loader.load(transaction);\n\n // THEN\n expect(result).toEqual([]);\n });\n });\n\n describe(\"loadField function\", () => {\n it(\"should return an error when field type if not supported\", async () => {\n const field: TransactionFieldContext = {\n type: ClearSignContextType.TOKEN,\n chainId: 7,\n address: \"0x1234\",\n };\n\n const loader = new TrustedNameContextLoader(mockTrustedNameDataSource);\n const result = await loader.loadField(field);\n\n expect(result).toEqual(null);\n });\n\n it(\"should return a payload\", async () => {\n // GIVEN\n const field: TransactionFieldContext = {\n type: ClearSignContextType.TRUSTED_NAME,\n chainId: 7,\n address: \"0x1234\",\n challenge: \"17\",\n sources: [\"ens\"],\n types: [\"eoa\"],\n };\n\n // WHEN\n vi.spyOn(\n mockTrustedNameDataSource,\n \"getTrustedNamePayload\",\n ).mockResolvedValue(Right(\"payload\"));\n const loader = new TrustedNameContextLoader(mockTrustedNameDataSource);\n const result = await loader.loadField(field);\n\n // THEN\n expect(result).toEqual({\n type: ClearSignContextType.TRUSTED_NAME,\n payload: \"payload\",\n });\n });\n\n it(\"should return an error when unable to fetch the datasource\", async () => {\n // GIVEN\n const field: TransactionFieldContext = {\n type: ClearSignContextType.TRUSTED_NAME,\n chainId: 7,\n address: \"0x1234\",\n challenge: \"17\",\n sources: [\"ens\"],\n types: [\"eoa\"],\n };\n\n // WHEN\n vi.spyOn(\n mockTrustedNameDataSource,\n \"getTrustedNamePayload\",\n ).mockResolvedValue(Left(new Error(\"error\")));\n const loader = new TrustedNameContextLoader(mockTrustedNameDataSource);\n const result = await loader.loadField(field);\n\n // THEN\n expect(result).toEqual({\n type: ClearSignContextType.ERROR,\n error: new Error(\"error\"),\n });\n });\n });\n});\n"],
5
- "mappings": "aAAA,IAAAA,EAA4B,qBAE5BC,EAAqC,2CAMrCC,EAAyC,0DAEzC,SAAS,2BAA4B,IAAM,CACzC,MAAMC,EAAmD,CACvD,qBAAsB,GAAG,GAAG,EAC5B,sBAAuB,GAAG,GAAG,CAC/B,EAEA,WAAW,IAAM,CACf,GAAG,gBAAgB,EACnB,GAAG,MACDA,EACA,sBACF,EAAE,qBAAkB,SAAM,SAAS,CAAC,CACtC,CAAC,EAED,SAAS,gBAAiB,SAAY,CACpC,GAAG,0DAA2D,SAAY,CACxE,MAAMC,EAAc,CAAC,EACfC,EAAS,IAAI,2BAAyBF,CAAyB,EAC/DG,EAAU,IAAMD,EAAO,KAAKD,CAAW,EAE7C,MAAM,OAAOE,EAAQ,CAAC,EAAE,SAAS,QAAQ,CAAC,CAAC,CAC7C,CAAC,EAED,GAAG,kDAAmD,SAAY,CAChE,MAAMF,EAAc,CAClB,OAAQ,8DACR,UAAW,WACb,EAGMG,EAAS,MADA,IAAI,2BAAyBJ,CAAyB,EACzC,KAAKC,CAAW,EAE5C,OAAOG,CAAM,EAAE,QAAQ,CACrB,CACE,KAAM,uBAAqB,MAC3B,MAAO,IAAI,MAAM,mDAAmD,CACtE,CACF,CAAC,CACH,CAAC,EAED,GAAG,kDAAmD,SAAY,CAChE,MAAMH,EAAc,CAClB,OAAQ,iBACR,UAAW,WACb,EAGMG,EAAS,MADA,IAAI,2BAAyBJ,CAAyB,EACzC,KAAKC,CAAW,EAE5C,OAAOG,CAAM,EAAE,QAAQ,CACrB,CACE,KAAM,uBAAqB,MAC3B,MAAO,IAAI,MAAM,mDAAmD,CACtE,CACF,CAAC,CACH,CAAC,EAED,GAAG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I,EAAS,MADA,IAAI,2BAAyBJ,CAAyB,EACzC,UAAUK,CAAK,EAG3C,OAAOD,CAAM,EAAE,QAAQ,CACrB,KAAM,uBAAqB,aAC3B,QAAS,SACX,CAAC,CACH,CAAC,EAED,GAAG,6DAA8D,SAAY,CAE3E,MAAMC,EAAiC,CACrC,KAAM,uBAAqB,aAC3B,QAAS,EACT,QAAS,SACT,UAAW,KACX,QAAS,CAAC,KAAK,EACf,MAAO,CAAC,KAAK,CACf,EAGA,GAAG,MACDL,EACA,uBACF,EAAE,qBAAkB,QAAK,IAAI,MAAM,OAAO,CAAC,CAAC,EAE5C,MAAMI,EAAS,MADA,IAAI,2BAAyBJ,CAAyB,EACzC,UAAUK,CAAK,EAG3C,OAAOD,CAAM,EAAE,QAAQ,CACrB,KAAM,uBAAqB,MAC3B,MAAO,IAAI,MAAM,OAAO,CAC1B,CAAC,CACH,CAAC,CACH,CAAC,CACH,CAAC",
4
+ "sourcesContent": ["import { Left, Right } from \"purify-ts\";\n\nimport { ClearSignContextType } from \"@/shared/model/ClearSignContext\";\nimport {\n type TransactionContext,\n type TransactionFieldContext,\n} from \"@/shared/model/TransactionContext\";\nimport { type TrustedNameDataSource } from \"@/trusted-name/data/TrustedNameDataSource\";\nimport { TrustedNameContextLoader } from \"@/trusted-name/domain/TrustedNameContextLoader\";\n\ndescribe(\"TrustedNameContextLoader\", () => {\n const mockTrustedNameDataSource: TrustedNameDataSource = {\n getDomainNamePayload: vi.fn(),\n getTrustedNamePayload: vi.fn(),\n };\n\n beforeEach(() => {\n vi.restoreAllMocks();\n vi.spyOn(\n mockTrustedNameDataSource,\n \"getDomainNamePayload\",\n ).mockResolvedValue(Right(\"payload\"));\n });\n\n describe(\"load function\", () => {\n it(\"should return an empty array when no domain or registry\", async () => {\n const transaction = {} as TransactionContext;\n const loader = new TrustedNameContextLoader(mockTrustedNameDataSource);\n const promise = () => loader.load(transaction);\n\n await expect(promise()).resolves.toEqual([]);\n });\n\n it(\"should return an error when domain > max length\", async () => {\n const transaction = {\n domain: \"maxlength-maxlength-maxlength-maxlength-maxlength-maxlength\",\n challenge: \"challenge\",\n } as TransactionContext;\n\n const loader = new TrustedNameContextLoader(mockTrustedNameDataSource);\n const result = await loader.load(transaction);\n\n expect(result).toEqual([\n {\n type: ClearSignContextType.ERROR,\n error: new Error(\"[ContextModule] TrustedNameLoader: invalid domain\"),\n },\n ]);\n });\n\n it(\"should return an error when domain is not valid\", async () => {\n const transaction = {\n domain: \"hello\uD83D\uDC4B\",\n challenge: \"challenge\",\n } as TransactionContext;\n\n const loader = new TrustedNameContextLoader(mockTrustedNameDataSource);\n const result = await loader.load(transaction);\n\n expect(result).toEqual([\n {\n type: ClearSignContextType.ERROR,\n error: new Error(\"[ContextModule] TrustedNameLoader: invalid domain\"),\n },\n ]);\n });\n\n it(\"should return a payload\", async () => {\n const transaction = {\n domain: \"hello.eth\",\n challenge: \"challenge\",\n } as TransactionContext;\n\n const loader = new TrustedNameContextLoader(mockTrustedNameDataSource);\n const result = await loader.load(transaction);\n\n expect(result).toEqual([\n {\n type: ClearSignContextType.TRUSTED_NAME,\n payload: \"payload\",\n },\n ]);\n });\n\n it(\"should return an error when unable to fetch the datasource\", async () => {\n // GIVEN\n const transaction = {\n domain: \"hello.eth\",\n challenge: \"challenge\",\n } as TransactionContext;\n\n // WHEN\n vi.spyOn(\n mockTrustedNameDataSource,\n \"getDomainNamePayload\",\n ).mockResolvedValue(Left(new Error(\"error\")));\n const loader = new TrustedNameContextLoader(mockTrustedNameDataSource);\n const result = await loader.load(transaction);\n\n // THEN\n expect(result).toEqual([\n { type: ClearSignContextType.ERROR, error: new Error(\"error\") },\n ]);\n });\n\n it(\"should return an empty array when no challenge\", async () => {\n // GIVEN\n const transaction = {\n domain: \"hello.eth\",\n challenge: undefined,\n } as TransactionContext;\n\n // WHEN\n const loader = new TrustedNameContextLoader(mockTrustedNameDataSource);\n const result = await loader.load(transaction);\n\n // THEN\n expect(result).toEqual([]);\n });\n });\n\n describe(\"loadField function\", () => {\n it(\"should return an error when field type if not supported\", async () => {\n const field: TransactionFieldContext = {\n type: ClearSignContextType.TOKEN,\n chainId: 7,\n address: \"0x1234\",\n };\n\n const loader = new TrustedNameContextLoader(mockTrustedNameDataSource);\n const result = await loader.loadField(field);\n\n expect(result).toEqual(null);\n });\n\n it(\"should return a payload\", async () => {\n // GIVEN\n const field: TransactionFieldContext = {\n type: ClearSignContextType.TRUSTED_NAME,\n chainId: 7,\n address: \"0x1234\",\n challenge: \"17\",\n sources: [\"ens\"],\n types: [\"eoa\"],\n };\n\n // WHEN\n vi.spyOn(\n mockTrustedNameDataSource,\n \"getTrustedNamePayload\",\n ).mockResolvedValue(Right(\"payload\"));\n const loader = new TrustedNameContextLoader(mockTrustedNameDataSource);\n const result = await loader.loadField(field);\n\n // THEN\n expect(result).toEqual({\n type: ClearSignContextType.TRUSTED_NAME,\n payload: \"payload\",\n });\n });\n\n it(\"should return an error when unable to fetch the datasource\", async () => {\n // GIVEN\n const field: TransactionFieldContext = {\n type: ClearSignContextType.TRUSTED_NAME,\n chainId: 7,\n address: \"0x1234\",\n challenge: \"17\",\n sources: [\"ens\"],\n types: [\"eoa\"],\n };\n\n // WHEN\n vi.spyOn(\n mockTrustedNameDataSource,\n \"getTrustedNamePayload\",\n ).mockResolvedValue(Left(new Error(\"error\")));\n const loader = new TrustedNameContextLoader(mockTrustedNameDataSource);\n const result = await loader.loadField(field);\n\n // THEN\n expect(result).toEqual({\n type: ClearSignContextType.ERROR,\n error: new Error(\"error\"),\n });\n });\n });\n});\n"],
5
+ "mappings": "aAAA,IAAAA,EAA4B,qBAE5BC,EAAqC,2CAMrCC,EAAyC,0DAEzC,SAAS,2BAA4B,IAAM,CACzC,MAAMC,EAAmD,CACvD,qBAAsB,GAAG,GAAG,EAC5B,sBAAuB,GAAG,GAAG,CAC/B,EAEA,WAAW,IAAM,CACf,GAAG,gBAAgB,EACnB,GAAG,MACDA,EACA,sBACF,EAAE,qBAAkB,SAAM,SAAS,C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CAAM,EAAE,QAAQ,CACrB,KAAM,uBAAqB,MAC3B,MAAO,IAAI,MAAM,OAAO,CAC1B,CAAC,CACH,CAAC,CACH,CAAC,CACH,CAAC",
6
6
  "names": ["import_purify_ts", "import_ClearSignContext", "import_TrustedNameContextLoader", "mockTrustedNameDataSource", "transaction", "loader", "promise", "result", "field"]
7
7
  }
@@ -1,2 +1,2 @@
1
- "use strict";var l=Object.defineProperty;var D=Object.getOwnPropertyDescriptor;var I=Object.getOwnPropertyNames;var w=Object.prototype.hasOwnProperty;var k=(r,t)=>{for(var e in t)l(r,e,{get:t[e],enumerable:!0})},H=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of I(t))!w.call(r,a)&&a!==e&&l(r,a,{get:()=>t[a],enumerable:!(n=D(t,a))||n.enumerable});return r};var b=r=>H(l({},"__esModule",{value:!0}),r),_=(r,t,e,n)=>{for(var a=n>1?void 0:n?D(t,e):t,o=r.length-1,i;o>=0;o--)(i=r[o])&&(a=(n?i(t,e,a):i(a))||a);return n&&a&&l(t,e,a),a},C=(r,t)=>(e,n)=>t(e,n,r);var R={};k(R,{UniswapContextLoader:()=>p});module.exports=b(R);var s=require("@ledgerhq/device-management-kit"),A=require("ethers"),c=require("inversify"),S=require("purify-ts"),g=require("../../shared/model/ClearSignContext"),T=require("../../token/di/tokenTypes"),f=require("../../uniswap/constants/plugin"),d=require("../../uniswap/constants/uniswap"),h=require("../../uniswap/di/uniswapTypes");let p=class{constructor(t,e){this.commandDecoderDataSource=t;this.tokenDataSource=e}async load(t){const{data:e,selector:n,chainId:a}=t;if(!(0,s.isHexaString)(e))return[];if(n!==d.UNISWAP_EXECUTE_SELECTOR)return[];const o=this._buildUniswapPluginCommandData(),i=await this._extractClearSignContexts(e,a);return i.length>0?[o,...i]:[]}_buildUniswapPluginCommandData(){const t=new s.ByteArrayBuilder().add8BitUIntToData(f.UNISWAP_PLUGIN_NAME.length).addAsciiStringToData(f.UNISWAP_PLUGIN_NAME).addBufferToData((0,s.hexaStringToBuffer)(d.UNISWAP_UNIVERSAL_ROUTER_ADDRESS)).addBufferToData((0,s.hexaStringToBuffer)(d.UNISWAP_EXECUTE_SELECTOR)).addBufferToData((0,s.hexaStringToBuffer)(f.UNISWAP_PLUGIN_SIGNATURE)).build();return{type:g.ClearSignContextType.EXTERNAL_PLUGIN,payload:(0,s.bufferToHexaString)(t).slice(2)}}async _extractClearSignContexts(t,e){try{const a=new A.Interface(d.UNISWAP_EXECUTE_ABI).parseTransaction({data:t}),o=a?.args[0],i=a?.args[1];if(!(0,s.isHexaString)(o)||!this._isHexaStringArray(i))return[];const x=this._extractCommands(o).orDefault([]);if(o.length===0||i.length!==x.length)return[];const y=x.reduce((m,u,U)=>{const N=i[U],E=this.commandDecoderDataSource.decode(u,N,e);return m.push([u,E]),m},[]);if(!this._isChainingSwapSupported(y))return[];const P=[...new Set(y.flatMap(([,m])=>m))];return(await Promise.all(P.map(m=>this.tokenDataSource.getTokenInfosPayload({address:m,chainId:e})))).map(m=>m.caseOf({Left:u=>({type:g.ClearSignContextType.ERROR,error:u}),Right:u=>({type:g.ClearSignContextType.TOKEN,payload:u})}))}catch{return[]}}_extractCommands(t){return S.Maybe.fromNullable(t.slice(2).match(/../g)).map(e=>e.map(n=>`0x${n}`)).map(e=>e.map(n=>d.UNISWAP_COMMANDS[n])).chain(e=>e.every(n=>n!==void 0)?S.Maybe.of(e):S.Nothing)}_isChainingSwapSupported(t){let e,n;for(const[a,o]of t){if(!d.UNISWAP_SWAP_COMMANDS.includes(a))continue;const i=a.slice(0,2);if(e&&(e!==o[0]||n!==i))return!1;e=o[o.length-1],n=i}return!0}_isHexaStringArray(t){return Array.isArray(t)&&t.every(e=>typeof e=="string"&&(0,s.isHexaString)(e))}};p=_([(0,c.injectable)(),C(0,(0,c.inject)(h.uniswapTypes.CommandDecoderDataSource)),C(1,(0,c.inject)(T.tokenTypes.TokenDataSource))],p);0&&(module.exports={UniswapContextLoader});
1
+ "use strict";var l=Object.defineProperty;var D=Object.getOwnPropertyDescriptor;var I=Object.getOwnPropertyNames;var w=Object.prototype.hasOwnProperty;var k=(r,t)=>{for(var e in t)l(r,e,{get:t[e],enumerable:!0})},H=(r,t,e,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of I(t))!w.call(r,n)&&n!==e&&l(r,n,{get:()=>t[n],enumerable:!(a=D(t,n))||a.enumerable});return r};var b=r=>H(l({},"__esModule",{value:!0}),r),_=(r,t,e,a)=>{for(var n=a>1?void 0:a?D(t,e):t,o=r.length-1,i;o>=0;o--)(i=r[o])&&(n=(a?i(t,e,n):i(n))||n);return a&&n&&l(t,e,n),n},C=(r,t)=>(e,a)=>t(e,a,r);var R={};k(R,{UniswapContextLoader:()=>p});module.exports=b(R);var s=require("@ledgerhq/device-management-kit"),A=require("ethers"),c=require("inversify"),S=require("purify-ts"),g=require("../../shared/model/ClearSignContext"),T=require("../../token/di/tokenTypes"),f=require("../../uniswap/constants/plugin"),d=require("../../uniswap/constants/uniswap"),h=require("../../uniswap/di/uniswapTypes");let p=class{constructor(t,e){this.commandDecoderDataSource=t;this.tokenDataSource=e}async load(t){const{data:e,selector:a,chainId:n}=t;if(!(0,s.isHexaString)(e))return[];if(a!==d.UNISWAP_EXECUTE_SELECTOR)return[];const o=this._buildUniswapPluginCommandData(),i=await this._extractClearSignContexts(e,n);return i.length>0?[o,...i]:[]}_buildUniswapPluginCommandData(){const t=new s.ByteArrayBuilder().add8BitUIntToData(f.UNISWAP_PLUGIN_NAME.length).addAsciiStringToData(f.UNISWAP_PLUGIN_NAME).addBufferToData((0,s.hexaStringToBuffer)(d.UNISWAP_UNIVERSAL_ROUTER_ADDRESS)).addBufferToData((0,s.hexaStringToBuffer)(d.UNISWAP_EXECUTE_SELECTOR)).addBufferToData((0,s.hexaStringToBuffer)(f.UNISWAP_PLUGIN_SIGNATURE)).build();return{type:g.ClearSignContextType.EXTERNAL_PLUGIN,payload:(0,s.bufferToHexaString)(t,!1)}}async _extractClearSignContexts(t,e){try{const n=new A.Interface(d.UNISWAP_EXECUTE_ABI).parseTransaction({data:t}),o=n?.args[0],i=n?.args[1];if(!(0,s.isHexaString)(o)||!this._isHexaStringArray(i))return[];const x=this._extractCommands(o).orDefault([]);if(o.length===0||i.length!==x.length)return[];const y=x.reduce((m,u,U)=>{const N=i[U],E=this.commandDecoderDataSource.decode(u,N,e);return m.push([u,E]),m},[]);if(!this._isChainingSwapSupported(y))return[];const P=[...new Set(y.flatMap(([,m])=>m))];return(await Promise.all(P.map(m=>this.tokenDataSource.getTokenInfosPayload({address:m,chainId:e})))).map(m=>m.caseOf({Left:u=>({type:g.ClearSignContextType.ERROR,error:u}),Right:u=>({type:g.ClearSignContextType.TOKEN,payload:u})}))}catch{return[]}}_extractCommands(t){return S.Maybe.fromNullable(t.slice(2).match(/../g)).map(e=>e.map(a=>`0x${a}`)).map(e=>e.map(a=>d.UNISWAP_COMMANDS[a])).chain(e=>e.every(a=>a!==void 0)?S.Maybe.of(e):S.Nothing)}_isChainingSwapSupported(t){let e,a;for(const[n,o]of t){if(!d.UNISWAP_SWAP_COMMANDS.includes(n))continue;const i=n.slice(0,2);if(e&&(e!==o[0]||a!==i))return!1;e=o[o.length-1],a=i}return!0}_isHexaStringArray(t){return Array.isArray(t)&&t.every(e=>typeof e=="string"&&(0,s.isHexaString)(e))}};p=_([(0,c.injectable)(),C(0,(0,c.inject)(h.uniswapTypes.CommandDecoderDataSource)),C(1,(0,c.inject)(T.tokenTypes.TokenDataSource))],p);0&&(module.exports={UniswapContextLoader});
2
2
  //# sourceMappingURL=UniswapContextLoader.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/uniswap/domain/UniswapContextLoader.ts"],
4
- "sourcesContent": ["import {\n bufferToHexaString,\n ByteArrayBuilder,\n HexaString,\n hexaStringToBuffer,\n isHexaString,\n} from \"@ledgerhq/device-management-kit\";\nimport { Interface } from \"ethers\";\nimport { inject, injectable } from \"inversify\";\nimport { Maybe, Nothing } from \"purify-ts\";\n\nimport { ContextLoader } from \"@/shared/domain/ContextLoader\";\nimport {\n ClearSignContext,\n ClearSignContextType,\n} from \"@/shared/model/ClearSignContext\";\nimport { TransactionContext } from \"@/shared/model/TransactionContext\";\nimport { type TokenDataSource } from \"@/token/data/TokenDataSource\";\nimport { tokenTypes } from \"@/token/di/tokenTypes\";\nimport {\n UNISWAP_PLUGIN_NAME,\n UNISWAP_PLUGIN_SIGNATURE,\n} from \"@/uniswap/constants/plugin\";\nimport {\n UNISWAP_COMMANDS,\n UNISWAP_EXECUTE_ABI,\n UNISWAP_EXECUTE_SELECTOR,\n UNISWAP_SWAP_COMMANDS,\n UNISWAP_UNIVERSAL_ROUTER_ADDRESS,\n UniswapSupportedCommand,\n} from \"@/uniswap/constants/uniswap\";\nimport { type CommandDecoderDataSource } from \"@/uniswap/data/CommandDecoderDataSource\";\nimport { uniswapTypes } from \"@/uniswap/di/uniswapTypes\";\n\n@injectable()\nexport class UniswapContextLoader implements ContextLoader {\n constructor(\n @inject(uniswapTypes.CommandDecoderDataSource)\n private commandDecoderDataSource: CommandDecoderDataSource,\n @inject(tokenTypes.TokenDataSource)\n private tokenDataSource: TokenDataSource,\n ) {}\n\n async load(ctx: TransactionContext): Promise<ClearSignContext[]> {\n const { data, selector, chainId } = ctx;\n if (!isHexaString(data)) {\n return [];\n }\n\n if (selector !== UNISWAP_EXECUTE_SELECTOR) {\n return [];\n }\n\n const externalPluginContext = this._buildUniswapPluginCommandData();\n const tokenContexts = await this._extractClearSignContexts(data, chainId);\n\n if (tokenContexts.length > 0)\n return [externalPluginContext, ...tokenContexts];\n\n return [];\n }\n\n /**\n * Constructs the external plugin context for Uniswap external plugin command.\n *\n * @private\n * @returns {ClearSignContext} - The generated external plugin context.\n */\n private _buildUniswapPluginCommandData(): ClearSignContext {\n const buffer = new ByteArrayBuilder()\n .add8BitUIntToData(UNISWAP_PLUGIN_NAME.length)\n .addAsciiStringToData(UNISWAP_PLUGIN_NAME)\n .addBufferToData(hexaStringToBuffer(UNISWAP_UNIVERSAL_ROUTER_ADDRESS)!)\n .addBufferToData(hexaStringToBuffer(UNISWAP_EXECUTE_SELECTOR)!)\n .addBufferToData(hexaStringToBuffer(UNISWAP_PLUGIN_SIGNATURE)!)\n .build();\n\n return {\n type: ClearSignContextType.EXTERNAL_PLUGIN,\n payload: bufferToHexaString(buffer).slice(2),\n };\n }\n\n /**\n * Extracts and decodes the clear sign contexts from a Uniswap calldata transaction.\n *\n * This function:\n * - Parses the calldata using the Uniswap `execute` function signature.\n * - Extracts and validates the `commands` and `inputs`.\n * - Decodes the commands and ensures they match the number of inputs.\n * - Extracts addresses used in the transaction and verifies if chaining swaps are supported.\n * - Fetches token information for unique addresses.\n * - Returns an array of `ClearSignContext` objects representing either token data or errors.\n *\n * @private\n * @param {HexaString} calldata - The raw calldata of the Uniswap transaction.\n * @param {number} chainId - The blockchain chain ID where the transaction is being executed.\n * @returns {Promise<ClearSignContext[]>} - A promise resolving to an array of clear sign contexts.\n */\n private async _extractClearSignContexts(\n calldata: HexaString,\n chainId: number,\n ): Promise<ClearSignContext[]> {\n try {\n const iface = new Interface(UNISWAP_EXECUTE_ABI);\n\n const tx = iface.parseTransaction({ data: calldata });\n const commands: unknown = tx?.args[0];\n const inputs: unknown = tx?.args[1];\n\n if (!isHexaString(commands) || !this._isHexaStringArray(inputs)) {\n return [];\n }\n\n const decodedCommands = this._extractCommands(commands).orDefault([]);\n if (commands.length === 0 || inputs.length !== decodedCommands.length) {\n // Invalid commands or inputs\n return [];\n }\n\n const addressesByCommand = decodedCommands.reduce(\n (acc, command, index) => {\n const input = inputs[index]!;\n const decoded: HexaString[] = this.commandDecoderDataSource.decode(\n command,\n input,\n chainId,\n );\n\n acc.push([command, decoded]);\n\n return acc;\n },\n [] as [UniswapSupportedCommand, HexaString[]][],\n );\n\n if (!this._isChainingSwapSupported(addressesByCommand)) {\n return [];\n }\n\n const uniqueAddresses = [\n ...new Set(addressesByCommand.flatMap(([, addresses]) => addresses)),\n ];\n\n const tokensPayload = await Promise.all(\n uniqueAddresses.map((address) =>\n this.tokenDataSource.getTokenInfosPayload({ address, chainId }),\n ),\n );\n\n return tokensPayload.map((either) =>\n either.caseOf<ClearSignContext>({\n Left: (error) => ({ type: ClearSignContextType.ERROR, error }),\n Right: (payload) => ({ type: ClearSignContextType.TOKEN, payload }),\n }),\n );\n } catch (_) {\n return [];\n }\n }\n\n /**\n * Extracts Uniswap-supported commands from a hexadecimal string.\n * Each command is represented by one byte (2 hex characters), and this function:\n * - Maps each command to a known Uniswap command.\n * - Returns `Nothing` if any extracted command is unsupported.\n *\n * @private\n * @param {HexaString} hex - A hexadecimal string representing commands.\n * @returns {Maybe<UniswapSupportedCommand[]>} - A `Maybe` containing an array of recognized commands, or `Nothing` if any command is unsupported.\n *\n * @example\n * // Valid command extraction\n * _extractCommands('0x0008');\n * // Returns: Just(['0x00', '0x08'])\n *\n * @example\n * // Contains an unsupported command (0x05 is not supported)\n * _extractCommands('0x0005');\n * // Returns: Nothing\n *\n * @example\n * // Empty or invalid input\n * _extractCommands('0x');\n * // Returns: Nothing\n */\n private _extractCommands(hex: HexaString): Maybe<UniswapSupportedCommand[]> {\n return Maybe.fromNullable(hex.slice(2).match(/../g))\n .map((bytes) => bytes.map((b) => `0x${b}` as HexaString))\n .map((hexBytes) => hexBytes.map((b) => UNISWAP_COMMANDS[b]))\n .chain((commands) =>\n commands.every((command) => command !== undefined)\n ? Maybe.of(commands as UniswapSupportedCommand[])\n : Nothing,\n );\n }\n\n /**\n * Checks if the provided swap commands can be chained together.\n * A valid chain requires that:\n * - The output asset of the previous swap matches the input asset of the next swap.\n * - The pool version remains consistent across swaps.\n *\n * @private\n * @param {Array<[UniswapSupportedCommand, HexaString[]]>} data - An array of tuples containing a swap command and associated addresses.\n * @returns {boolean} - Returns `true` if the swap commands form a valid chain, otherwise `false`.\n *\n * @example\n * // Valid chaining: same output/input asset and pool version\n * _isChainingSwapSupported([\n * ['0x08', ['0xABC', '0xDEF']],\n * ['0x08', ['0xDEF', '0x123']]\n * ]);\n * // Returns: true\n *\n * @example\n * // Invalid chaining: different pool versions\n * _isChainingSwapSupported([\n * ['0x08', ['0xABC', '0xDEF']],\n * ['0x01', ['0xDEF', '0x123']]\n * ]);\n * // Returns: false\n *\n * @example\n * // Invalid chaining: output does not match next input\n * _isChainingSwapSupported([\n * ['0x01A1', ['0xABC', '0xDEF']],\n * ['0x01B2', ['0xXYZ', '0x123']]\n * ]);\n * // Returns: false\n */\n private _isChainingSwapSupported(\n data: [UniswapSupportedCommand, HexaString[]][],\n ): boolean {\n let lastAsset: HexaString | undefined = undefined;\n let lastPoolVersion: string | undefined = undefined;\n\n for (const [command, addresses] of data) {\n if (!UNISWAP_SWAP_COMMANDS.includes(command)) continue; // Ignore non-swap commands\n\n const poolVersion = command.slice(0, 2);\n\n if (\n lastAsset &&\n (lastAsset !== addresses[0] || lastPoolVersion !== poolVersion)\n ) {\n // Invalid chaining, return empty array\n return false;\n }\n\n // update last asset and pool version\n lastAsset = addresses[addresses.length - 1];\n lastPoolVersion = poolVersion;\n }\n\n return true;\n }\n\n /**\n * Checks if a given value is an array of hexadecimal strings.\n *\n * @private\n * @param {unknown} array - The value to check.\n * @returns {array is HexaString[]} - `true` if the value is an array of hexadecimal strings, otherwise `false`.\n */\n private _isHexaStringArray(array: unknown): array is HexaString[] {\n return (\n Array.isArray(array) &&\n array.every((item) => typeof item === \"string\" && isHexaString(item))\n );\n }\n}\n"],
5
- "mappings": "okBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,0BAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAMO,2CACPC,EAA0B,kBAC1BC,EAAmC,qBACnCC,EAA+B,qBAG/BC,EAGO,2CAGPC,EAA2B,iCAC3BC,EAGO,sCACPC,EAOO,uCAEPC,EAA6B,qCAGtB,IAAMC,EAAN,KAAoD,CACzD,YAEUC,EAEAC,EACR,CAHQ,8BAAAD,EAEA,qBAAAC,CACP,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AAO,EACT,CASQ,mBAAmBC,EAAuC,CAChE,OACE,MAAM,QAAQA,CAAK,GACnBA,EAAM,MAAOC,GAAS,OAAOA,GAAS,aAAY,gBAAaA,CAAI,CAAC,CAExE,CACF,EA5OanC,EAANoC,EAAA,IADN,cAAW,EAGPC,EAAA,eAAO,eAAa,wBAAwB,GAE5CA,EAAA,eAAO,aAAW,eAAe,IAJzBrC",
4
+ "sourcesContent": ["import {\n bufferToHexaString,\n ByteArrayBuilder,\n HexaString,\n hexaStringToBuffer,\n isHexaString,\n} from \"@ledgerhq/device-management-kit\";\nimport { Interface } from \"ethers\";\nimport { inject, injectable } from \"inversify\";\nimport { Maybe, Nothing } from \"purify-ts\";\n\nimport { ContextLoader } from \"@/shared/domain/ContextLoader\";\nimport {\n ClearSignContext,\n ClearSignContextType,\n} from \"@/shared/model/ClearSignContext\";\nimport { TransactionContext } from \"@/shared/model/TransactionContext\";\nimport { type TokenDataSource } from \"@/token/data/TokenDataSource\";\nimport { tokenTypes } from \"@/token/di/tokenTypes\";\nimport {\n UNISWAP_PLUGIN_NAME,\n UNISWAP_PLUGIN_SIGNATURE,\n} from \"@/uniswap/constants/plugin\";\nimport {\n UNISWAP_COMMANDS,\n UNISWAP_EXECUTE_ABI,\n UNISWAP_EXECUTE_SELECTOR,\n UNISWAP_SWAP_COMMANDS,\n UNISWAP_UNIVERSAL_ROUTER_ADDRESS,\n UniswapSupportedCommand,\n} from \"@/uniswap/constants/uniswap\";\nimport { type CommandDecoderDataSource } from \"@/uniswap/data/CommandDecoderDataSource\";\nimport { uniswapTypes } from \"@/uniswap/di/uniswapTypes\";\n\n@injectable()\nexport class UniswapContextLoader implements ContextLoader {\n constructor(\n @inject(uniswapTypes.CommandDecoderDataSource)\n private commandDecoderDataSource: CommandDecoderDataSource,\n @inject(tokenTypes.TokenDataSource)\n private tokenDataSource: TokenDataSource,\n ) {}\n\n async load(ctx: TransactionContext): Promise<ClearSignContext[]> {\n const { data, selector, chainId } = ctx;\n if (!isHexaString(data)) {\n return [];\n }\n\n if (selector !== UNISWAP_EXECUTE_SELECTOR) {\n return [];\n }\n\n const externalPluginContext = this._buildUniswapPluginCommandData();\n const tokenContexts = await this._extractClearSignContexts(data, chainId);\n\n if (tokenContexts.length > 0)\n return [externalPluginContext, ...tokenContexts];\n\n return [];\n }\n\n /**\n * Constructs the external plugin context for Uniswap external plugin command.\n *\n * @private\n * @returns {ClearSignContext} - The generated external plugin context.\n */\n private _buildUniswapPluginCommandData(): ClearSignContext {\n const buffer = new ByteArrayBuilder()\n .add8BitUIntToData(UNISWAP_PLUGIN_NAME.length)\n .addAsciiStringToData(UNISWAP_PLUGIN_NAME)\n .addBufferToData(hexaStringToBuffer(UNISWAP_UNIVERSAL_ROUTER_ADDRESS)!)\n .addBufferToData(hexaStringToBuffer(UNISWAP_EXECUTE_SELECTOR)!)\n .addBufferToData(hexaStringToBuffer(UNISWAP_PLUGIN_SIGNATURE)!)\n .build();\n\n return {\n type: ClearSignContextType.EXTERNAL_PLUGIN,\n payload: bufferToHexaString(buffer, false),\n };\n }\n\n /**\n * Extracts and decodes the clear sign contexts from a Uniswap calldata transaction.\n *\n * This function:\n * - Parses the calldata using the Uniswap `execute` function signature.\n * - Extracts and validates the `commands` and `inputs`.\n * - Decodes the commands and ensures they match the number of inputs.\n * - Extracts addresses used in the transaction and verifies if chaining swaps are supported.\n * - Fetches token information for unique addresses.\n * - Returns an array of `ClearSignContext` objects representing either token data or errors.\n *\n * @private\n * @param {HexaString} calldata - The raw calldata of the Uniswap transaction.\n * @param {number} chainId - The blockchain chain ID where the transaction is being executed.\n * @returns {Promise<ClearSignContext[]>} - A promise resolving to an array of clear sign contexts.\n */\n private async _extractClearSignContexts(\n calldata: HexaString,\n chainId: number,\n ): Promise<ClearSignContext[]> {\n try {\n const iface = new Interface(UNISWAP_EXECUTE_ABI);\n\n const tx = iface.parseTransaction({ data: calldata });\n const commands: unknown = tx?.args[0];\n const inputs: unknown = tx?.args[1];\n\n if (!isHexaString(commands) || !this._isHexaStringArray(inputs)) {\n return [];\n }\n\n const decodedCommands = this._extractCommands(commands).orDefault([]);\n if (commands.length === 0 || inputs.length !== decodedCommands.length) {\n // Invalid commands or inputs\n return [];\n }\n\n const addressesByCommand = decodedCommands.reduce(\n (acc, command, index) => {\n const input = inputs[index]!;\n const decoded: HexaString[] = this.commandDecoderDataSource.decode(\n command,\n input,\n chainId,\n );\n\n acc.push([command, decoded]);\n\n return acc;\n },\n [] as [UniswapSupportedCommand, HexaString[]][],\n );\n\n if (!this._isChainingSwapSupported(addressesByCommand)) {\n return [];\n }\n\n const uniqueAddresses = [\n ...new Set(addressesByCommand.flatMap(([, addresses]) => addresses)),\n ];\n\n const tokensPayload = await Promise.all(\n uniqueAddresses.map((address) =>\n this.tokenDataSource.getTokenInfosPayload({ address, chainId }),\n ),\n );\n\n return tokensPayload.map((either) =>\n either.caseOf<ClearSignContext>({\n Left: (error) => ({ type: ClearSignContextType.ERROR, error }),\n Right: (payload) => ({ type: ClearSignContextType.TOKEN, payload }),\n }),\n );\n } catch (_) {\n return [];\n }\n }\n\n /**\n * Extracts Uniswap-supported commands from a hexadecimal string.\n * Each command is represented by one byte (2 hex characters), and this function:\n * - Maps each command to a known Uniswap command.\n * - Returns `Nothing` if any extracted command is unsupported.\n *\n * @private\n * @param {HexaString} hex - A hexadecimal string representing commands.\n * @returns {Maybe<UniswapSupportedCommand[]>} - A `Maybe` containing an array of recognized commands, or `Nothing` if any command is unsupported.\n *\n * @example\n * // Valid command extraction\n * _extractCommands('0x0008');\n * // Returns: Just(['0x00', '0x08'])\n *\n * @example\n * // Contains an unsupported command (0x05 is not supported)\n * _extractCommands('0x0005');\n * // Returns: Nothing\n *\n * @example\n * // Empty or invalid input\n * _extractCommands('0x');\n * // Returns: Nothing\n */\n private _extractCommands(hex: HexaString): Maybe<UniswapSupportedCommand[]> {\n return Maybe.fromNullable(hex.slice(2).match(/../g))\n .map((bytes) => bytes.map((b) => `0x${b}` as HexaString))\n .map((hexBytes) => hexBytes.map((b) => UNISWAP_COMMANDS[b]))\n .chain((commands) =>\n commands.every((command) => command !== undefined)\n ? Maybe.of(commands as UniswapSupportedCommand[])\n : Nothing,\n );\n }\n\n /**\n * Checks if the provided swap commands can be chained together.\n * A valid chain requires that:\n * - The output asset of the previous swap matches the input asset of the next swap.\n * - The pool version remains consistent across swaps.\n *\n * @private\n * @param {Array<[UniswapSupportedCommand, HexaString[]]>} data - An array of tuples containing a swap command and associated addresses.\n * @returns {boolean} - Returns `true` if the swap commands form a valid chain, otherwise `false`.\n *\n * @example\n * // Valid chaining: same output/input asset and pool version\n * _isChainingSwapSupported([\n * ['0x08', ['0xABC', '0xDEF']],\n * ['0x08', ['0xDEF', '0x123']]\n * ]);\n * // Returns: true\n *\n * @example\n * // Invalid chaining: different pool versions\n * _isChainingSwapSupported([\n * ['0x08', ['0xABC', '0xDEF']],\n * ['0x01', ['0xDEF', '0x123']]\n * ]);\n * // Returns: false\n *\n * @example\n * // Invalid chaining: output does not match next input\n * _isChainingSwapSupported([\n * ['0x01A1', ['0xABC', '0xDEF']],\n * ['0x01B2', ['0xXYZ', '0x123']]\n * ]);\n * // Returns: false\n */\n private _isChainingSwapSupported(\n data: [UniswapSupportedCommand, HexaString[]][],\n ): boolean {\n let lastAsset: HexaString | undefined = undefined;\n let lastPoolVersion: string | undefined = undefined;\n\n for (const [command, addresses] of data) {\n if (!UNISWAP_SWAP_COMMANDS.includes(command)) continue; // Ignore non-swap commands\n\n const poolVersion = command.slice(0, 2);\n\n if (\n lastAsset &&\n (lastAsset !== addresses[0] || lastPoolVersion !== poolVersion)\n ) {\n // Invalid chaining, return empty array\n return false;\n }\n\n // update last asset and pool version\n lastAsset = addresses[addresses.length - 1];\n lastPoolVersion = poolVersion;\n }\n\n return true;\n }\n\n /**\n * Checks if a given value is an array of hexadecimal strings.\n *\n * @private\n * @param {unknown} array - The value to check.\n * @returns {array is HexaString[]} - `true` if the value is an array of hexadecimal strings, otherwise `false`.\n */\n private _isHexaStringArray(array: unknown): array is HexaString[] {\n return (\n Array.isArray(array) &&\n array.every((item) => typeof item === \"string\" && isHexaString(item))\n );\n }\n}\n"],
5
+ "mappings": "okBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,0BAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAMO,2CACPC,EAA0B,kBAC1BC,EAAmC,qBACnCC,EAA+B,qBAG/BC,EAGO,2CAGPC,EAA2B,iCAC3BC,EAGO,sCACPC,EAOO,uCAEPC,EAA6B,qCAGtB,IAAMC,EAAN,KAAoD,CACzD,YAEUC,EAEAC,EACR,CAHQ,8BAAAD,EAEA,qBAAAC,CACP,CAEH,MAAM,KAAKC,EAAsD,CAC/D,KAAM,CAAE,KAAAC,EAAM,SAAAC,EAAU,QAAAC,CAAQ,EAAIH,EACpC,GAAI,IAAC,gBAAaC,CAAI,EACpB,MAAO,CAAC,EAGV,GAAIC,IAAa,2BACf,MAAO,CAAC,EAGV,MAAME,EAAwB,KAAK,+BAA+B,EAC5DC,EAAgB,MAAM,KAAK,0BAA0BJ,EAAME,CAAO,EAExE,OAAIE,EAAc,OAAS,EAClB,CAACD,EAAuB,GAAGC,CAAa,EAE1C,CAAC,CACV,CAQQ,gCAAmD,CACzD,MAAMC,EAAS,IAAI,mBAAiB,EACjC,kBAAkB,sBAAoB,MAAM,EAC5C,qBAAqB,qBAAmB,EACxC,mBAAgB,sBAAmB,kCAAgC,CAAE,EACrE,mBAAgB,sBAAmB,0BAAwB,CAAE,EAC7D,mBAAgB,sBAAmB,0BAAwB,CAAE,EAC7D,MAAM,EAET,MAAO,CACL,KAAM,uBAAqB,gBAC3B,WAAS,sBAAmBA,EAAQ,EAAK,CAC3C,CACF,CAkBA,MAAc,0BACZC,EACAJ,EAC6B,CAC7B,GAAI,CAGF,MAAMK,EAFQ,IAAI,YAAU,qBAAmB,EAE9B,iBAAiB,CAAE,KAAMD,CAAS,CAAC,EAC9CE,EAAoBD,GAAI,KAAK,CAAC,EAC9BE,EAA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A,EAAS,MAAOK,GAAYA,IAAY,MAAS,EAC7C,QAAM,GAAGL,CAAqC,EAC9C,SACN,CACJ,CAoCQ,yBACNR,EACS,CACT,IAAI2B,EACAC,EAEJ,SAAW,CAACf,EAASK,CAAS,IAAKlB,EAAM,CACvC,GAAI,CAAC,wBAAsB,SAASa,CAAO,EAAG,SAE9C,MAAMgB,EAAchB,EAAQ,MAAM,EAAG,CAAC,EAEtC,GACEc,IACCA,IAAcT,EAAU,CAAC,GAAKU,IAAoBC,GAGnD,MAAO,GAITF,EAAYT,EAAUA,EAAU,OAAS,CAAC,EAC1CU,EAAkBC,CACpB,CAEA,MAAO,EACT,CASQ,mBAAmBC,EAAuC,CAChE,OACE,MAAM,QAAQA,CAAK,GACnBA,EAAM,MAAOC,GAAS,OAAOA,GAAS,aAAY,gBAAaA,CAAI,CAAC,CAExE,CACF,EA5OanC,EAANoC,EAAA,IADN,cAAW,EAGPC,EAAA,eAAO,eAAa,wBAAwB,GAE5CA,EAAA,eAAO,aAAW,eAAe,IAJzBrC",
6
6
  "names": ["UniswapContextLoader_exports", "__export", "UniswapContextLoader", "__toCommonJS", "import_device_management_kit", "import_ethers", "import_inversify", "import_purify_ts", "import_ClearSignContext", "import_tokenTypes", "import_plugin", "import_uniswap", "import_uniswapTypes", "UniswapContextLoader", "commandDecoderDataSource", "tokenDataSource", "ctx", "data", "selector", "chainId", "externalPluginContext", "tokenContexts", "buffer", "calldata", "tx", "commands", "inputs", "decodedCommands", "addressesByCommand", "acc", "command", "index", "input", "decoded", "uniqueAddresses", "addresses", "address", "either", "error", "payload", "hex", "bytes", "b", "hexBytes", "lastAsset", "lastPoolVersion", "poolVersion", "array", "item", "__decorateClass", "__decorateParam"]
7
7
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ledgerhq/context-module",
3
- "version": "1.6.0",
3
+ "version": "1.7.0",
4
4
  "private": false,
5
5
  "license": "Apache-2.0",
6
6
  "exports": {
@@ -1,2 +1,2 @@
1
- import{DefaultContextModule as t}from"./DefaultContextModule";const o="https://crypto-assets-service.api.ledger.com/v1",r="https://web3checks-backend.api.ledger.com/v3",n="https://nft.api.live.ledger.com/v1",i={cal:{url:o,mode:"prod",branch:"main"},web3checks:{url:r},metadataService:{url:n},defaultLoaders:!0,customLoaders:[],customTypedDataLoader:void 0,customSolanaLoader:void 0};class s{config=i;needOriginToken=!0;originToken;constructor({originToken:e}={}){this.originToken=e}removeDefaultLoaders(){return this.config.defaultLoaders=!1,this}addLoader(e){return this.config.customLoaders.push(e),this}addTypedDataLoader(e){return this.config.customTypedDataLoader=e,this}addWeb3CheckLoader(e){return this.needOriginToken=!1,this.config.customWeb3CheckLoader=e,this}addSolanaLoader(e){return this.config.customSolanaLoader=e,this}setCalConfig(e){return this.config.cal=e,this}setMetadataServiceConfig(e){return this.config.metadataService=e,this}setWeb3ChecksConfig(e){return this.config.web3checks=e,this}build(){if(this.needOriginToken&&!this.originToken)throw new Error("Origin token is required");const e={...this.config,originToken:this.originToken};return new t(e)}}export{s as ContextModuleBuilder,i as DEFAULT_CONFIG};
1
+ import{DefaultContextModule as t}from"./DefaultContextModule";const o="https://crypto-assets-service.api.ledger.com/v1",r="https://web3checks-backend.api.ledger.com/v3",n="https://nft.api.live.ledger.com",i={cal:{url:o,mode:"prod",branch:"main"},web3checks:{url:r},metadataServiceDomain:{url:n},defaultLoaders:!0,customLoaders:[],customTypedDataLoader:void 0,customSolanaLoader:void 0};class s{config=i;needOriginToken=!0;originToken;constructor({originToken:e}={}){this.originToken=e}removeDefaultLoaders(){return this.config.defaultLoaders=!1,this}addLoader(e){return this.config.customLoaders.push(e),this}addTypedDataLoader(e){return this.config.customTypedDataLoader=e,this}addWeb3CheckLoader(e){return this.needOriginToken=!1,this.config.customWeb3CheckLoader=e,this}addSolanaLoader(e){return this.config.customSolanaLoader=e,this}setCalConfig(e){return this.config.cal=e,this}setMetadataServiceConfig(e){return this.config.metadataServiceDomain=e,this}setWeb3ChecksConfig(e){return this.config.web3checks=e,this}build(){if(this.needOriginToken&&!this.originToken)throw new Error("Origin token is required");const e={...this.config,originToken:this.originToken};return new t(e)}}export{s as ContextModuleBuilder,i as DEFAULT_CONFIG};
2
2
  //# sourceMappingURL=ContextModuleBuilder.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/ContextModuleBuilder.ts"],
4
- "sourcesContent": ["import { type ContextModuleConstructorArgs } from \"./config/model/ContextModuleBuildArgs\";\nimport {\n type ContextModuleCalConfig,\n type ContextModuleConfig,\n type ContextModuleMetadataServiceConfig,\n type ContextModuleWeb3ChecksConfig,\n} from \"./config/model/ContextModuleConfig\";\nimport { type ContextLoader } from \"./shared/domain/ContextLoader\";\nimport { type SolanaContextLoader } from \"./solana/domain/SolanaContextLoader\";\nimport { type TypedDataContextLoader } from \"./typed-data/domain/TypedDataContextLoader\";\nimport { type Web3CheckContextLoader } from \"./web3-check/domain/Web3CheckContextLoader\";\nimport { type ContextModule } from \"./ContextModule\";\nimport { DefaultContextModule } from \"./DefaultContextModule\";\n\nconst DEFAULT_CAL_URL = \"https://crypto-assets-service.api.ledger.com/v1\";\nconst DEFAULT_WEB3_CHECKS_URL = \"https://web3checks-backend.api.ledger.com/v3\";\nconst DEFAULT_METADATA_SERVICE_URL = \"https://nft.api.live.ledger.com/v1\";\n\nexport const DEFAULT_CONFIG: ContextModuleConfig = {\n cal: {\n url: DEFAULT_CAL_URL,\n mode: \"prod\",\n branch: \"main\",\n },\n web3checks: {\n url: DEFAULT_WEB3_CHECKS_URL,\n },\n metadataService: {\n url: DEFAULT_METADATA_SERVICE_URL,\n },\n defaultLoaders: true,\n customLoaders: [],\n customTypedDataLoader: undefined,\n customSolanaLoader: undefined,\n};\n\nexport class ContextModuleBuilder {\n private config: ContextModuleConfig = DEFAULT_CONFIG;\n private needOriginToken: boolean = true;\n private originToken?: string;\n\n constructor({ originToken }: ContextModuleConstructorArgs = {}) {\n this.originToken = originToken;\n }\n\n /**\n * Remove default loaders from the list of loaders\n *\n * @returns this\n */\n removeDefaultLoaders() {\n this.config.defaultLoaders = false;\n return this;\n }\n\n /**\n * Add a custom loader to the list of loaders\n *\n * @param loader loader to add to the list of loaders\n * @returns this\n */\n addLoader(loader: ContextLoader) {\n this.config.customLoaders.push(loader);\n return this;\n }\n\n /**\n * Replace the default loader for typed data clear signing contexts\n *\n * @param loader loader to use for typed data clear signing contexts\n * @returns this\n */\n addTypedDataLoader(loader: TypedDataContextLoader) {\n this.config.customTypedDataLoader = loader;\n return this;\n }\n\n /**\n * Replace the default loader for web3 checks\n *\n * @param loader loader to use for web3 checks\n * @returns this\n */\n addWeb3CheckLoader(loader: Web3CheckContextLoader) {\n this.needOriginToken = false;\n this.config.customWeb3CheckLoader = loader;\n return this;\n }\n\n /**\n * Replace the default loader for Solana context\n *\n * @param loader loader to use for Solana context\n * @returns this\n */\n addSolanaLoader(loader: SolanaContextLoader) {\n this.config.customSolanaLoader = loader;\n return this;\n }\n\n /**\n * Add a custom CAL configuration\n *\n * @param calConfig\n * @returns this\n */\n setCalConfig(calConfig: ContextModuleCalConfig) {\n this.config.cal = calConfig;\n return this;\n }\n\n /**\n * Add a custom metadata service configuration\n *\n * @param metadataServiceConfig\n * @returns this\n */\n setMetadataServiceConfig(\n metadataServiceConfig: ContextModuleMetadataServiceConfig,\n ) {\n this.config.metadataService = metadataServiceConfig;\n return this;\n }\n\n /**\n * Add a custom web3 checks configuration\n *\n * @param web3ChecksConfig\n * @returns this\n */\n setWeb3ChecksConfig(web3ChecksConfig: ContextModuleWeb3ChecksConfig) {\n this.config.web3checks = web3ChecksConfig;\n return this;\n }\n\n /**\n * Build the context module\n *\n * @returns the context module\n */\n build(): ContextModule {\n if (this.needOriginToken && !this.originToken) {\n throw new Error(\"Origin token is required\");\n }\n\n const config = { ...this.config, originToken: this.originToken };\n return new DefaultContextModule(config);\n }\n}\n"],
5
- "mappings": "AAYA,OAAS,wBAAAA,MAA4B,yBAErC,MAAMC,EAAkB,kDAClBC,EAA0B,+CAC1BC,EAA+B,qCAExBC,EAAsC,CACjD,IAAK,CACH,IAAKH,EACL,KAAM,OACN,OAAQ,MACV,EACA,WAAY,CACV,IAAKC,CACP,EACA,gBAAiB,CACf,IAAKC,CACP,EACA,eAAgB,GAChB,cAAe,CAAC,EAChB,sBAAuB,OACvB,mBAAoB,MACtB,EAEO,MAAME,CAAqB,CACxB,OAA8BD,EAC9B,gBAA2B,GAC3B,YAER,YAAY,CAAE,YAAAE,CAAY,EAAkC,CAAC,EAAG,CAC9D,KAAK,YAAcA,CACrB,CAOA,sBAAuB,CACrB,YAAK,OAAO,eAAiB,GACtB,IACT,CAQA,UAAUC,EAAuB,CAC/B,YAAK,OAAO,cAAc,KAAKA,CAAM,EAC9B,IACT,CAQA,mBAAmBA,EAAgC,CACjD,YAAK,OAAO,sBAAwBA,EAC7B,IACT,CAQA,mBAAmBA,EAAgC,CACjD,YAAK,gBAAkB,GACvB,KAAK,OAAO,sBAAwBA,EAC7B,IACT,CAQA,gBAAgBA,EAA6B,CAC3C,YAAK,OAAO,mBAAqBA,EAC1B,IACT,CAQA,aAAaC,EAAmC,CAC9C,YAAK,OAAO,IAAMA,EACX,IACT,CAQA,yBACEC,EACA,CACA,YAAK,OAAO,gBAAkBA,EACvB,IACT,CAQA,oBAAoBC,EAAiD,CACnE,YAAK,OAAO,WAAaA,EAClB,IACT,CAOA,OAAuB,CACrB,GAAI,KAAK,iBAAmB,CAAC,KAAK,YAChC,MAAM,IAAI,MAAM,0BAA0B,EAG5C,MAAMC,EAAS,CAAE,GAAG,KAAK,OAAQ,YAAa,KAAK,WAAY,EAC/D,OAAO,IAAIX,EAAqBW,CAAM,CACxC,CACF",
6
- "names": ["DefaultContextModule", "DEFAULT_CAL_URL", "DEFAULT_WEB3_CHECKS_URL", "DEFAULT_METADATA_SERVICE_URL", "DEFAULT_CONFIG", "ContextModuleBuilder", "originToken", "loader", "calConfig", "metadataServiceConfig", "web3ChecksConfig", "config"]
4
+ "sourcesContent": ["import { type ContextModuleConstructorArgs } from \"./config/model/ContextModuleBuildArgs\";\nimport {\n type ContextModuleCalConfig,\n type ContextModuleConfig,\n type ContextModuleMetadataServiceConfig,\n type ContextModuleWeb3ChecksConfig,\n} from \"./config/model/ContextModuleConfig\";\nimport { type ContextLoader } from \"./shared/domain/ContextLoader\";\nimport { type SolanaContextLoader } from \"./solana/domain/SolanaContextLoader\";\nimport { type TypedDataContextLoader } from \"./typed-data/domain/TypedDataContextLoader\";\nimport { type Web3CheckContextLoader } from \"./web3-check/domain/Web3CheckContextLoader\";\nimport { type ContextModule } from \"./ContextModule\";\nimport { DefaultContextModule } from \"./DefaultContextModule\";\n\nconst DEFAULT_CAL_URL = \"https://crypto-assets-service.api.ledger.com/v1\";\nconst DEFAULT_WEB3_CHECKS_URL = \"https://web3checks-backend.api.ledger.com/v3\";\nconst DEFAULT_METADATA_SERVICE_DOMAIN = \"https://nft.api.live.ledger.com\";\n\nexport const DEFAULT_CONFIG: ContextModuleConfig = {\n cal: {\n url: DEFAULT_CAL_URL,\n mode: \"prod\",\n branch: \"main\",\n },\n web3checks: {\n url: DEFAULT_WEB3_CHECKS_URL,\n },\n metadataServiceDomain: {\n url: DEFAULT_METADATA_SERVICE_DOMAIN,\n },\n defaultLoaders: true,\n customLoaders: [],\n customTypedDataLoader: undefined,\n customSolanaLoader: undefined,\n};\n\nexport class ContextModuleBuilder {\n private config: ContextModuleConfig = DEFAULT_CONFIG;\n private needOriginToken: boolean = true;\n private originToken?: string;\n\n constructor({ originToken }: ContextModuleConstructorArgs = {}) {\n this.originToken = originToken;\n }\n\n /**\n * Remove default loaders from the list of loaders\n *\n * @returns this\n */\n removeDefaultLoaders() {\n this.config.defaultLoaders = false;\n return this;\n }\n\n /**\n * Add a custom loader to the list of loaders\n *\n * @param loader loader to add to the list of loaders\n * @returns this\n */\n addLoader(loader: ContextLoader) {\n this.config.customLoaders.push(loader);\n return this;\n }\n\n /**\n * Replace the default loader for typed data clear signing contexts\n *\n * @param loader loader to use for typed data clear signing contexts\n * @returns this\n */\n addTypedDataLoader(loader: TypedDataContextLoader) {\n this.config.customTypedDataLoader = loader;\n return this;\n }\n\n /**\n * Replace the default loader for web3 checks\n *\n * @param loader loader to use for web3 checks\n * @returns this\n */\n addWeb3CheckLoader(loader: Web3CheckContextLoader) {\n this.needOriginToken = false;\n this.config.customWeb3CheckLoader = loader;\n return this;\n }\n\n /**\n * Replace the default loader for Solana context\n *\n * @param loader loader to use for Solana context\n * @returns this\n */\n addSolanaLoader(loader: SolanaContextLoader) {\n this.config.customSolanaLoader = loader;\n return this;\n }\n\n /**\n * Add a custom CAL configuration\n *\n * @param calConfig\n * @returns this\n */\n setCalConfig(calConfig: ContextModuleCalConfig) {\n this.config.cal = calConfig;\n return this;\n }\n\n /**\n * Add a custom metadata service configuration\n *\n * @param metadataServiceConfig\n * @returns this\n */\n setMetadataServiceConfig(\n metadataServiceConfig: ContextModuleMetadataServiceConfig,\n ) {\n this.config.metadataServiceDomain = metadataServiceConfig;\n return this;\n }\n\n /**\n * Add a custom web3 checks configuration\n *\n * @param web3ChecksConfig\n * @returns this\n */\n setWeb3ChecksConfig(web3ChecksConfig: ContextModuleWeb3ChecksConfig) {\n this.config.web3checks = web3ChecksConfig;\n return this;\n }\n\n /**\n * Build the context module\n *\n * @returns the context module\n */\n build(): ContextModule {\n if (this.needOriginToken && !this.originToken) {\n throw new Error(\"Origin token is required\");\n }\n\n const config = { ...this.config, originToken: this.originToken };\n return new DefaultContextModule(config);\n }\n}\n"],
5
+ "mappings": "AAYA,OAAS,wBAAAA,MAA4B,yBAErC,MAAMC,EAAkB,kDAClBC,EAA0B,+CAC1BC,EAAkC,kCAE3BC,EAAsC,CACjD,IAAK,CACH,IAAKH,EACL,KAAM,OACN,OAAQ,MACV,EACA,WAAY,CACV,IAAKC,CACP,EACA,sBAAuB,CACrB,IAAKC,CACP,EACA,eAAgB,GAChB,cAAe,CAAC,EAChB,sBAAuB,OACvB,mBAAoB,MACtB,EAEO,MAAME,CAAqB,CACxB,OAA8BD,EAC9B,gBAA2B,GAC3B,YAER,YAAY,CAAE,YAAAE,CAAY,EAAkC,CAAC,EAAG,CAC9D,KAAK,YAAcA,CACrB,CAOA,sBAAuB,CACrB,YAAK,OAAO,eAAiB,GACtB,IACT,CAQA,UAAUC,EAAuB,CAC/B,YAAK,OAAO,cAAc,KAAKA,CAAM,EAC9B,IACT,CAQA,mBAAmBA,EAAgC,CACjD,YAAK,OAAO,sBAAwBA,EAC7B,IACT,CAQA,mBAAmBA,EAAgC,CACjD,YAAK,gBAAkB,GACvB,KAAK,OAAO,sBAAwBA,EAC7B,IACT,CAQA,gBAAgBA,EAA6B,CAC3C,YAAK,OAAO,mBAAqBA,EAC1B,IACT,CAQA,aAAaC,EAAmC,CAC9C,YAAK,OAAO,IAAMA,EACX,IACT,CAQA,yBACEC,EACA,CACA,YAAK,OAAO,sBAAwBA,EAC7B,IACT,CAQA,oBAAoBC,EAAiD,CACnE,YAAK,OAAO,WAAaA,EAClB,IACT,CAOA,OAAuB,CACrB,GAAI,KAAK,iBAAmB,CAAC,KAAK,YAChC,MAAM,IAAI,MAAM,0BAA0B,EAG5C,MAAMC,EAAS,CAAE,GAAG,KAAK,OAAQ,YAAa,KAAK,WAAY,EAC/D,OAAO,IAAIX,EAAqBW,CAAM,CACxC,CACF",
6
+ "names": ["DefaultContextModule", "DEFAULT_CAL_URL", "DEFAULT_WEB3_CHECKS_URL", "DEFAULT_METADATA_SERVICE_DOMAIN", "DEFAULT_CONFIG", "ContextModuleBuilder", "originToken", "loader", "calConfig", "metadataServiceConfig", "web3ChecksConfig", "config"]
7
7
  }
@@ -1,2 +1,2 @@
1
- import{configTypes as s}from"./config/di/configTypes";import{ContextModuleBuilder as c}from"./ContextModuleBuilder";import{DefaultContextModule as r}from"./DefaultContextModule";describe("ContextModuleBuilder",()=>{const d={url:"https://cal/v1",mode:"prod",branch:"main"},a={url:"https://web3checks/v1"},i={originToken:"test"};beforeEach(()=>{vi.resetAllMocks()}),it("should return a default context module",()=>{const e=new c(i).build();expect(e).toBeInstanceOf(r)}),it("should return a custom context module",()=>{const t=new c(i),e={load:vi.fn()},o=t.removeDefaultLoaders().addLoader(e).build();expect(o).toBeInstanceOf(r)}),it("should return a custom context module with a custom typed data loader",()=>{const t=new c(i),e={load:vi.fn()},o=t.removeDefaultLoaders().addTypedDataLoader(e).build();expect(o).toBeInstanceOf(r),expect(o._typedDataLoader).toBe(e)}),it("should return a custom context module with a custom config",()=>{const e=new c(i).setCalConfig(d).setWeb3ChecksConfig(a).build(),o=e._container.get(s.Config);expect(e).toBeInstanceOf(r),expect(o.cal).toEqual(d),expect(o.web3checks).toEqual(a)}),it("should return a custom context module with a custom custom web3checks loader",()=>{const t=new c,e={load:vi.fn()},o=t.removeDefaultLoaders().addWeb3CheckLoader(e).build();expect(o).toBeInstanceOf(r),expect(o._web3CheckLoader).toBe(e)}),it("should throw an error if origin token is not provided",()=>{const t=new c;expect(()=>t.build()).toThrow("Origin token is required")}),it("should not throw an error if origin token is provided",()=>{const t=new c(i);expect(()=>t.build()).not.toThrow()}),it("should not throw an error if origin token is not provided and addWeb3CheckLoader is called",()=>{const t=new c;expect(()=>t.addWeb3CheckLoader({load:vi.fn()}).build()).not.toThrow()}),describe("setMetadataServiceConfig",()=>{it("should set the metadata service configuration",()=>{const t=new c(i),e={url:"https://custom-metadata-service.com/v3"},o=t.setMetadataServiceConfig(e).build(),n=o._container.get(s.Config);expect(o).toBeInstanceOf(r),expect(n.metadataService).toEqual(e)}),it("should override the default metadata service configuration",()=>{const t=new c(i),e={url:"https://override-metadata-service.com/v1"},n=t.setMetadataServiceConfig(e).build()._container.get(s.Config);expect(n.metadataService.url).toBe(e.url),expect(n.metadataService.url).not.toBe("https://nft.api.live.ledger.com/v2")})}),describe("setCalConfig",()=>{it("should set the CAL configuration",()=>{const t=new c(i),e={url:"https://custom-cal-service.com/v2",mode:"test",branch:"next"},o=t.setCalConfig(e).build(),n=o._container.get(s.Config);expect(o).toBeInstanceOf(r),expect(n.cal).toEqual(e)}),it("should override the default CAL configuration",()=>{const t=new c(i),e={url:"https://override-cal-service.com/v1",mode:"prod",branch:"demo"},n=t.setCalConfig(e).build()._container.get(s.Config);expect(n.cal.url).toBe(e.url),expect(n.cal.mode).toBe(e.mode),expect(n.cal.branch).toBe(e.branch),expect(n.cal.url).not.toBe("https://crypto-assets-service.api.ledger.com/v1")})}),describe("setWeb3ChecksConfig",()=>{it("should set the web3 checks configuration",()=>{const t=new c(i),e={url:"https://custom-web3checks-service.com/v4"},o=t.setWeb3ChecksConfig(e).build(),n=o._container.get(s.Config);expect(o).toBeInstanceOf(r),expect(n.web3checks).toEqual(e)}),it("should override the default web3 checks configuration",()=>{const t=new c(i),e={url:"https://override-web3checks-service.com/v2"},n=t.setWeb3ChecksConfig(e).build()._container.get(s.Config);expect(n.web3checks.url).toBe(e.url),expect(n.web3checks.url).not.toBe("https://web3checks-backend.api.ledger.com/v3")})})});
1
+ import{configTypes as s}from"./config/di/configTypes";import{ContextModuleBuilder as c}from"./ContextModuleBuilder";import{DefaultContextModule as r}from"./DefaultContextModule";describe("ContextModuleBuilder",()=>{const d={url:"https://cal/v1",mode:"prod",branch:"main"},a={url:"https://web3checks/v1"},i={originToken:"test"};beforeEach(()=>{vi.resetAllMocks()}),it("should return a default context module",()=>{const e=new c(i).build();expect(e).toBeInstanceOf(r)}),it("should return a custom context module",()=>{const t=new c(i),e={load:vi.fn()},o=t.removeDefaultLoaders().addLoader(e).build();expect(o).toBeInstanceOf(r)}),it("should return a custom context module with a custom typed data loader",()=>{const t=new c(i),e={load:vi.fn()},o=t.removeDefaultLoaders().addTypedDataLoader(e).build();expect(o).toBeInstanceOf(r),expect(o._typedDataLoader).toBe(e)}),it("should return a custom context module with a custom config",()=>{const e=new c(i).setCalConfig(d).setWeb3ChecksConfig(a).build(),o=e._container.get(s.Config);expect(e).toBeInstanceOf(r),expect(o.cal).toEqual(d),expect(o.web3checks).toEqual(a)}),it("should return a custom context module with a custom custom web3checks loader",()=>{const t=new c,e={load:vi.fn()},o=t.removeDefaultLoaders().addWeb3CheckLoader(e).build();expect(o).toBeInstanceOf(r),expect(o._web3CheckLoader).toBe(e)}),it("should throw an error if origin token is not provided",()=>{const t=new c;expect(()=>t.build()).toThrow("Origin token is required")}),it("should not throw an error if origin token is provided",()=>{const t=new c(i);expect(()=>t.build()).not.toThrow()}),it("should not throw an error if origin token is not provided and addWeb3CheckLoader is called",()=>{const t=new c;expect(()=>t.addWeb3CheckLoader({load:vi.fn()}).build()).not.toThrow()}),describe("setMetadataServiceConfig",()=>{it("should set the metadata service configuration",()=>{const t=new c(i),e={url:"https://custom-metadata-service.com/v3"},o=t.setMetadataServiceConfig(e).build(),n=o._container.get(s.Config);expect(o).toBeInstanceOf(r),expect(n.metadataServiceDomain).toEqual(e)}),it("should override the default metadata service configuration",()=>{const t=new c(i),e={url:"https://override-metadata-service.com/v1"},n=t.setMetadataServiceConfig(e).build()._container.get(s.Config);expect(n.metadataServiceDomain.url).toBe(e.url),expect(n.metadataServiceDomain.url).not.toBe("https://nft.api.live.ledger.com/v2")})}),describe("setCalConfig",()=>{it("should set the CAL configuration",()=>{const t=new c(i),e={url:"https://custom-cal-service.com/v2",mode:"test",branch:"next"},o=t.setCalConfig(e).build(),n=o._container.get(s.Config);expect(o).toBeInstanceOf(r),expect(n.cal).toEqual(e)}),it("should override the default CAL configuration",()=>{const t=new c(i),e={url:"https://override-cal-service.com/v1",mode:"prod",branch:"demo"},n=t.setCalConfig(e).build()._container.get(s.Config);expect(n.cal.url).toBe(e.url),expect(n.cal.mode).toBe(e.mode),expect(n.cal.branch).toBe(e.branch),expect(n.cal.url).not.toBe("https://crypto-assets-service.api.ledger.com/v1")})}),describe("setWeb3ChecksConfig",()=>{it("should set the web3 checks configuration",()=>{const t=new c(i),e={url:"https://custom-web3checks-service.com/v4"},o=t.setWeb3ChecksConfig(e).build(),n=o._container.get(s.Config);expect(o).toBeInstanceOf(r),expect(n.web3checks).toEqual(e)}),it("should override the default web3 checks configuration",()=>{const t=new c(i),e={url:"https://override-web3checks-service.com/v2"},n=t.setWeb3ChecksConfig(e).build()._container.get(s.Config);expect(n.web3checks.url).toBe(e.url),expect(n.web3checks.url).not.toBe("https://web3checks-backend.api.ledger.com/v3")})})});
2
2
  //# sourceMappingURL=ContextModuleBuilder.test.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/ContextModuleBuilder.test.ts"],
4
- "sourcesContent": ["import { type Container } from \"inversify\";\n\nimport { configTypes } from \"./config/di/configTypes\";\nimport { type ContextModuleConstructorArgs } from \"./config/model/ContextModuleBuildArgs\";\nimport {\n type ContextModuleCalConfig,\n type ContextModuleConfig,\n type ContextModuleMetadataServiceConfig,\n} from \"./config/model/ContextModuleConfig\";\nimport { ContextModuleBuilder } from \"./ContextModuleBuilder\";\nimport { DefaultContextModule } from \"./DefaultContextModule\";\n\ndescribe(\"ContextModuleBuilder\", () => {\n const defaultCalConfig: ContextModuleCalConfig = {\n url: \"https://cal/v1\",\n mode: \"prod\",\n branch: \"main\",\n };\n const defaultWeb3ChecksConfig = {\n url: \"https://web3checks/v1\",\n };\n const defaultBuilderArgs: ContextModuleConstructorArgs = {\n originToken: \"test\",\n };\n\n beforeEach(() => {\n vi.resetAllMocks();\n });\n\n it(\"should return a default context module\", () => {\n const contextModuleBuilder = new ContextModuleBuilder(defaultBuilderArgs);\n\n const res = contextModuleBuilder.build();\n\n expect(res).toBeInstanceOf(DefaultContextModule);\n });\n\n it(\"should return a custom context module\", () => {\n const contextModuleBuilder = new ContextModuleBuilder(defaultBuilderArgs);\n const customLoader = { load: vi.fn() };\n\n const res = contextModuleBuilder\n .removeDefaultLoaders()\n .addLoader(customLoader)\n .build();\n\n expect(res).toBeInstanceOf(DefaultContextModule);\n });\n\n it(\"should return a custom context module with a custom typed data loader\", () => {\n const contextModuleBuilder = new ContextModuleBuilder(defaultBuilderArgs);\n const customLoader = { load: vi.fn() };\n\n const res = contextModuleBuilder\n .removeDefaultLoaders()\n .addTypedDataLoader(customLoader)\n .build();\n\n expect(res).toBeInstanceOf(DefaultContextModule);\n // @ts-expect-error _typedDataLoader is private\n expect(res[\"_typedDataLoader\"]).toBe(customLoader);\n });\n\n it(\"should return a custom context module with a custom config\", () => {\n const contextModuleBuilder = new ContextModuleBuilder(defaultBuilderArgs);\n\n const res = contextModuleBuilder\n .setCalConfig(defaultCalConfig)\n .setWeb3ChecksConfig(defaultWeb3ChecksConfig)\n .build();\n // @ts-expect-error _container is private\n const config = (res[\"_container\"] as Container).get<ContextModuleConfig>(\n configTypes.Config,\n );\n\n expect(res).toBeInstanceOf(DefaultContextModule);\n expect(config.cal).toEqual(defaultCalConfig);\n expect(config.web3checks).toEqual(defaultWeb3ChecksConfig);\n });\n\n it(\"should return a custom context module with a custom custom web3checks loader\", () => {\n const contextModuleBuilder = new ContextModuleBuilder();\n const customLoader = { load: vi.fn() };\n\n const res = contextModuleBuilder\n .removeDefaultLoaders()\n .addWeb3CheckLoader(customLoader)\n .build();\n\n expect(res).toBeInstanceOf(DefaultContextModule);\n // @ts-expect-error _web3CheckLoader is private\n expect(res[\"_web3CheckLoader\"]).toBe(customLoader);\n });\n\n it(\"should throw an error if origin token is not provided\", () => {\n const contextModuleBuilder = new ContextModuleBuilder();\n\n expect(() => contextModuleBuilder.build()).toThrow(\n \"Origin token is required\",\n );\n });\n\n it(\"should not throw an error if origin token is provided\", () => {\n const contextModuleBuilder = new ContextModuleBuilder(defaultBuilderArgs);\n\n expect(() => contextModuleBuilder.build()).not.toThrow();\n });\n\n it(\"should not throw an error if origin token is not provided and addWeb3CheckLoader is called\", () => {\n const contextModuleBuilder = new ContextModuleBuilder();\n\n expect(() =>\n contextModuleBuilder.addWeb3CheckLoader({ load: vi.fn() }).build(),\n ).not.toThrow();\n });\n\n describe(\"setMetadataServiceConfig\", () => {\n it(\"should set the metadata service configuration\", () => {\n const contextModuleBuilder = new ContextModuleBuilder(defaultBuilderArgs);\n const customMetadataConfig: ContextModuleMetadataServiceConfig = {\n url: \"https://custom-metadata-service.com/v3\",\n };\n\n const res = contextModuleBuilder\n .setMetadataServiceConfig(customMetadataConfig)\n .build();\n const config = (res as DefaultContextModule)[\n \"_container\"\n ].get<ContextModuleConfig>(configTypes.Config);\n\n expect(res).toBeInstanceOf(DefaultContextModule);\n expect(config.metadataService).toEqual(customMetadataConfig);\n });\n\n it(\"should override the default metadata service configuration\", () => {\n const contextModuleBuilder = new ContextModuleBuilder(defaultBuilderArgs);\n const customMetadataConfig: ContextModuleMetadataServiceConfig = {\n url: \"https://override-metadata-service.com/v1\",\n };\n\n const res = contextModuleBuilder\n .setMetadataServiceConfig(customMetadataConfig)\n .build();\n const config = (res as DefaultContextModule)[\n \"_container\"\n ].get<ContextModuleConfig>(configTypes.Config);\n\n expect(config.metadataService.url).toBe(customMetadataConfig.url);\n expect(config.metadataService.url).not.toBe(\n \"https://nft.api.live.ledger.com/v2\",\n );\n });\n });\n\n describe(\"setCalConfig\", () => {\n it(\"should set the CAL configuration\", () => {\n const contextModuleBuilder = new ContextModuleBuilder(defaultBuilderArgs);\n const customCalConfig: ContextModuleCalConfig = {\n url: \"https://custom-cal-service.com/v2\",\n mode: \"test\",\n branch: \"next\",\n };\n\n const res = contextModuleBuilder.setCalConfig(customCalConfig).build();\n const config = (res as DefaultContextModule)[\n \"_container\"\n ].get<ContextModuleConfig>(configTypes.Config);\n\n expect(res).toBeInstanceOf(DefaultContextModule);\n expect(config.cal).toEqual(customCalConfig);\n });\n\n it(\"should override the default CAL configuration\", () => {\n const contextModuleBuilder = new ContextModuleBuilder(defaultBuilderArgs);\n const customCalConfig: ContextModuleCalConfig = {\n url: \"https://override-cal-service.com/v1\",\n mode: \"prod\",\n branch: \"demo\",\n };\n\n const res = contextModuleBuilder.setCalConfig(customCalConfig).build();\n const config = (res as DefaultContextModule)[\n \"_container\"\n ].get<ContextModuleConfig>(configTypes.Config);\n\n expect(config.cal.url).toBe(customCalConfig.url);\n expect(config.cal.mode).toBe(customCalConfig.mode);\n expect(config.cal.branch).toBe(customCalConfig.branch);\n expect(config.cal.url).not.toBe(\n \"https://crypto-assets-service.api.ledger.com/v1\",\n );\n });\n });\n\n describe(\"setWeb3ChecksConfig\", () => {\n it(\"should set the web3 checks configuration\", () => {\n const contextModuleBuilder = new ContextModuleBuilder(defaultBuilderArgs);\n const customWeb3ChecksConfig = {\n url: \"https://custom-web3checks-service.com/v4\",\n };\n\n const res = contextModuleBuilder\n .setWeb3ChecksConfig(customWeb3ChecksConfig)\n .build();\n const config = (res as DefaultContextModule)[\n \"_container\"\n ].get<ContextModuleConfig>(configTypes.Config);\n\n expect(res).toBeInstanceOf(DefaultContextModule);\n expect(config.web3checks).toEqual(customWeb3ChecksConfig);\n });\n\n it(\"should override the default web3 checks configuration\", () => {\n const contextModuleBuilder = new ContextModuleBuilder(defaultBuilderArgs);\n const customWeb3ChecksConfig = {\n url: \"https://override-web3checks-service.com/v2\",\n };\n\n const res = contextModuleBuilder\n .setWeb3ChecksConfig(customWeb3ChecksConfig)\n .build();\n const config = (res as DefaultContextModule)[\n \"_container\"\n ].get<ContextModuleConfig>(configTypes.Config);\n\n expect(config.web3checks.url).toBe(customWeb3ChecksConfig.url);\n expect(config.web3checks.url).not.toBe(\n \"https://web3checks-backend.api.ledger.com/v3\",\n );\n });\n });\n});\n"],
5
- "mappings": "AAEA,OAAS,eAAAA,MAAmB,0BAO5B,OAAS,wBAAAC,MAA4B,yBACrC,OAAS,wBAAAC,MAA4B,yBAErC,SAAS,uBAAwB,IAAM,CACrC,MAAMC,EAA2C,CAC/C,IAAK,iBACL,KAAM,OACN,OAAQ,MACV,EACMC,EAA0B,CAC9B,IAAK,uBACP,EACMC,EAAmD,CACvD,YAAa,MACf,EAEA,WAAW,IAAM,CACf,GAAG,cAAc,CACnB,CAAC,EAED,GAAG,yCAA0C,IAAM,CAGjD,MAAMC,EAFuB,IAAIL,EAAqBI,CAAkB,EAEvC,MAAM,EAEvC,OAA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ify\";\n\nimport { configTypes } from \"./config/di/configTypes\";\nimport { type ContextModuleConstructorArgs } from \"./config/model/ContextModuleBuildArgs\";\nimport {\n type ContextModuleCalConfig,\n type ContextModuleConfig,\n type ContextModuleMetadataServiceConfig,\n} from \"./config/model/ContextModuleConfig\";\nimport { ContextModuleBuilder } from \"./ContextModuleBuilder\";\nimport { DefaultContextModule } from \"./DefaultContextModule\";\n\ndescribe(\"ContextModuleBuilder\", () => {\n const defaultCalConfig: ContextModuleCalConfig = {\n url: \"https://cal/v1\",\n mode: \"prod\",\n branch: \"main\",\n };\n const defaultWeb3ChecksConfig = {\n url: \"https://web3checks/v1\",\n };\n const defaultBuilderArgs: ContextModuleConstructorArgs = {\n originToken: \"test\",\n };\n\n beforeEach(() => {\n vi.resetAllMocks();\n });\n\n it(\"should return a default context module\", () => {\n const contextModuleBuilder = new ContextModuleBuilder(defaultBuilderArgs);\n\n const res = contextModuleBuilder.build();\n\n expect(res).toBeInstanceOf(DefaultContextModule);\n });\n\n it(\"should return a custom context module\", () => {\n const contextModuleBuilder = new ContextModuleBuilder(defaultBuilderArgs);\n const customLoader = { load: vi.fn() };\n\n const res = contextModuleBuilder\n .removeDefaultLoaders()\n .addLoader(customLoader)\n .build();\n\n expect(res).toBeInstanceOf(DefaultContextModule);\n });\n\n it(\"should return a custom context module with a custom typed data loader\", () => {\n const contextModuleBuilder = new ContextModuleBuilder(defaultBuilderArgs);\n const customLoader = { load: vi.fn() };\n\n const res = contextModuleBuilder\n .removeDefaultLoaders()\n .addTypedDataLoader(customLoader)\n .build();\n\n expect(res).toBeInstanceOf(DefaultContextModule);\n // @ts-expect-error _typedDataLoader is private\n expect(res[\"_typedDataLoader\"]).toBe(customLoader);\n });\n\n it(\"should return a custom context module with a custom config\", () => {\n const contextModuleBuilder = new ContextModuleBuilder(defaultBuilderArgs);\n\n const res = contextModuleBuilder\n .setCalConfig(defaultCalConfig)\n .setWeb3ChecksConfig(defaultWeb3ChecksConfig)\n .build();\n // @ts-expect-error _container is private\n const config = (res[\"_container\"] as Container).get<ContextModuleConfig>(\n configTypes.Config,\n );\n\n expect(res).toBeInstanceOf(DefaultContextModule);\n expect(config.cal).toEqual(defaultCalConfig);\n expect(config.web3checks).toEqual(defaultWeb3ChecksConfig);\n });\n\n it(\"should return a custom context module with a custom custom web3checks loader\", () => {\n const contextModuleBuilder = new ContextModuleBuilder();\n const customLoader = { load: vi.fn() };\n\n const res = contextModuleBuilder\n .removeDefaultLoaders()\n .addWeb3CheckLoader(customLoader)\n .build();\n\n expect(res).toBeInstanceOf(DefaultContextModule);\n // @ts-expect-error _web3CheckLoader is private\n expect(res[\"_web3CheckLoader\"]).toBe(customLoader);\n });\n\n it(\"should throw an error if origin token is not provided\", () => {\n const contextModuleBuilder = new ContextModuleBuilder();\n\n expect(() => contextModuleBuilder.build()).toThrow(\n \"Origin token is required\",\n );\n });\n\n it(\"should not throw an error if origin token is provided\", () => {\n const contextModuleBuilder = new ContextModuleBuilder(defaultBuilderArgs);\n\n expect(() => contextModuleBuilder.build()).not.toThrow();\n });\n\n it(\"should not throw an error if origin token is not provided and addWeb3CheckLoader is called\", () => {\n const contextModuleBuilder = new ContextModuleBuilder();\n\n expect(() =>\n contextModuleBuilder.addWeb3CheckLoader({ load: vi.fn() }).build(),\n ).not.toThrow();\n });\n\n describe(\"setMetadataServiceConfig\", () => {\n it(\"should set the metadata service configuration\", () => {\n const contextModuleBuilder = new ContextModuleBuilder(defaultBuilderArgs);\n const customMetadataConfig: ContextModuleMetadataServiceConfig = {\n url: \"https://custom-metadata-service.com/v3\",\n };\n\n const res = contextModuleBuilder\n .setMetadataServiceConfig(customMetadataConfig)\n .build();\n const config = (res as DefaultContextModule)[\n \"_container\"\n ].get<ContextModuleConfig>(configTypes.Config);\n\n expect(res).toBeInstanceOf(DefaultContextModule);\n expect(config.metadataServiceDomain).toEqual(customMetadataConfig);\n });\n\n it(\"should override the default metadata service configuration\", () => {\n const contextModuleBuilder = new ContextModuleBuilder(defaultBuilderArgs);\n const customMetadataConfig: ContextModuleMetadataServiceConfig = {\n url: \"https://override-metadata-service.com/v1\",\n };\n\n const res = contextModuleBuilder\n .setMetadataServiceConfig(customMetadataConfig)\n .build();\n const config = (res as DefaultContextModule)[\n \"_container\"\n ].get<ContextModuleConfig>(configTypes.Config);\n\n expect(config.metadataServiceDomain.url).toBe(customMetadataConfig.url);\n expect(config.metadataServiceDomain.url).not.toBe(\n \"https://nft.api.live.ledger.com/v2\",\n );\n });\n });\n\n describe(\"setCalConfig\", () => {\n it(\"should set the CAL configuration\", () => {\n const contextModuleBuilder = new ContextModuleBuilder(defaultBuilderArgs);\n const customCalConfig: ContextModuleCalConfig = {\n url: \"https://custom-cal-service.com/v2\",\n mode: \"test\",\n branch: \"next\",\n };\n\n const res = contextModuleBuilder.setCalConfig(customCalConfig).build();\n const config = (res as DefaultContextModule)[\n \"_container\"\n ].get<ContextModuleConfig>(configTypes.Config);\n\n expect(res).toBeInstanceOf(DefaultContextModule);\n expect(config.cal).toEqual(customCalConfig);\n });\n\n it(\"should override the default CAL configuration\", () => {\n const contextModuleBuilder = new ContextModuleBuilder(defaultBuilderArgs);\n const customCalConfig: ContextModuleCalConfig = {\n url: \"https://override-cal-service.com/v1\",\n mode: \"prod\",\n branch: \"demo\",\n };\n\n const res = contextModuleBuilder.setCalConfig(customCalConfig).build();\n const config = (res as DefaultContextModule)[\n \"_container\"\n ].get<ContextModuleConfig>(configTypes.Config);\n\n expect(config.cal.url).toBe(customCalConfig.url);\n expect(config.cal.mode).toBe(customCalConfig.mode);\n expect(config.cal.branch).toBe(customCalConfig.branch);\n expect(config.cal.url).not.toBe(\n \"https://crypto-assets-service.api.ledger.com/v1\",\n );\n });\n });\n\n describe(\"setWeb3ChecksConfig\", () => {\n it(\"should set the web3 checks configuration\", () => {\n const contextModuleBuilder = new ContextModuleBuilder(defaultBuilderArgs);\n const customWeb3ChecksConfig = {\n url: \"https://custom-web3checks-service.com/v4\",\n };\n\n const res = contextModuleBuilder\n .setWeb3ChecksConfig(customWeb3ChecksConfig)\n .build();\n const config = (res as DefaultContextModule)[\n \"_container\"\n ].get<ContextModuleConfig>(configTypes.Config);\n\n expect(res).toBeInstanceOf(DefaultContextModule);\n expect(config.web3checks).toEqual(customWeb3ChecksConfig);\n });\n\n it(\"should override the default web3 checks configuration\", () => {\n const contextModuleBuilder = new ContextModuleBuilder(defaultBuilderArgs);\n const customWeb3ChecksConfig = {\n url: \"https://override-web3checks-service.com/v2\",\n };\n\n const res = contextModuleBuilder\n .setWeb3ChecksConfig(customWeb3ChecksConfig)\n .build();\n const config = (res as DefaultContextModule)[\n \"_container\"\n ].get<ContextModuleConfig>(configTypes.Config);\n\n expect(config.web3checks.url).toBe(customWeb3ChecksConfig.url);\n expect(config.web3checks.url).not.toBe(\n \"https://web3checks-backend.api.ledger.com/v3\",\n );\n });\n });\n});\n"],
5
+ "mappings": "AAEA,OAAS,eAAAA,MAAmB,0BAO5B,OAAS,wBAAAC,MAA4B,yBACrC,OAAS,wBAAAC,MAA4B,yBAErC,SAAS,uBAAwB,IAAM,CACrC,MAAMC,EAA2C,CAC/C,IAAK,iBACL,KAAM,OACN,OAAQ,MACV,EACMC,EAA0B,CAC9B,IAAK,uBACP,EACMC,EAAmD,CACvD,YAAa,MACf,EAEA,WAAW,IAAM,CACf,GAAG,cAAc,CACnB,CAAC,EAED,GAAG,yCAA0C,IAAM,CAGjD,MAAMC,EAFuB,IAAIL,EAAqBI,CAAkB,EAEvC,MAAM,EAEvC,OAAOC,CAAG,EAAE,eAAeJ,CAAoB,CACjD,CAAC,EAED,GAAG,wCAAyC,IAAM,CAChD,MAAMK,EAAuB,IAAIN,EAAqBI,CAAkB,EAClEG,EAAe,CAAE,KAAM,GAAG,GAAG,CAAE,EAE/BF,EAAMC,EACT,qBAAqB,EACrB,UAAUC,CAAY,EACtB,MAAM,EAET,OAAOF,CAAG,EAAE,eAAeJ,CAAoB,CACjD,CAAC,EAED,GAAG,wEAAyE,IAAM,CAChF,MAAMK,EA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S,EAAO,IAAI,GAAG,EAAE,KAAKE,EAAgB,GAAG,EAC/C,OAAOF,EAAO,IAAI,IAAI,EAAE,KAAKE,EAAgB,IAAI,EACjD,OAAOF,EAAO,IAAI,MAAM,EAAE,KAAKE,EAAgB,MAAM,EACrD,OAAOF,EAAO,IAAI,GAAG,EAAE,IAAI,KACzB,iDACF,CACF,CAAC,CACH,CAAC,EAED,SAAS,sBAAuB,IAAM,CACpC,GAAG,2CAA4C,IAAM,CACnD,MAAMF,EAAuB,IAAIN,EAAqBI,CAAkB,EAClEO,EAAyB,CAC7B,IAAK,0CACP,EAEMN,EAAMC,EACT,oBAAoBK,CAAsB,EAC1C,MAAM,EACHH,EAAUH,EACd,WACA,IAAyBN,EAAY,MAAM,EAE7C,OAAOM,CAAG,EAAE,eAAeJ,CAAoB,EAC/C,OAAOO,EAAO,UAAU,EAAE,QAAQG,CAAsB,CAC1D,CAAC,EAED,GAAG,wDAAyD,IAAM,CAChE,MAAML,EAAuB,IAAIN,EAAqBI,CAAkB,EAClEO,EAAyB,CAC7B,IAAK,4CACP,EAKMH,EAHMF,EACT,oBAAoBK,CAAsB,EAC1C,MAAM,EAEP,WACA,IAAyBZ,EAAY,MAAM,EAE7C,OAAOS,EAAO,WAAW,GAAG,EAAE,KAAKG,EAAuB,GAAG,EAC7D,OAAOH,EAAO,WAAW,GAAG,EAAE,IAAI,KAChC,8CACF,CACF,CAAC,CACH,CAAC,CACH,CAAC",
6
6
  "names": ["configTypes", "ContextModuleBuilder", "DefaultContextModule", "defaultCalConfig", "defaultWeb3ChecksConfig", "defaultBuilderArgs", "res", "contextModuleBuilder", "customLoader", "config", "customMetadataConfig", "customCalConfig", "customWeb3ChecksConfig"]
7
7
  }
@@ -1,2 +1,2 @@
1
- import{Left as n}from"purify-ts";import{transactionTypes as i}from"./transaction/di/transactionTypes";import{trustedNameTypes as p}from"./trusted-name/di/trustedNameTypes";import{externalPluginTypes as s}from"./external-plugin/di/externalPluginTypes";import{nftTypes as d}from"./nft/di/nftTypes";import{ClearSignContextType as r}from"./shared/model/ClearSignContext";import{solanaContextTypes as C}from"./solana/di/solanaContextTypes";import{tokenTypes as l}from"./token/di/tokenTypes";import{typedDataTypes as m}from"./typed-data/di/typedDataTypes";import{uniswapTypes as x}from"./uniswap/di/uniswapTypes";import{web3CheckTypes as c}from"./web3-check/di/web3CheckTypes";import{makeContainer as y}from"./di";class P{_container;_loaders;_typedDataLoader;_web3CheckLoader;_solanaLoader;constructor(e){this._container=y({config:e}),this._loaders=e.defaultLoaders?this._getDefaultLoaders():[],this._loaders.push(...e.customLoaders),this._typedDataLoader=e.customTypedDataLoader??this._getDefaultTypedDataLoader(),this._web3CheckLoader=e.customWeb3CheckLoader??this._getWeb3CheckLoader(),this._solanaLoader=e.customSolanaLoader??this._getSolanaLoader()}_getDefaultLoaders(){return[this._container.get(s.ExternalPluginContextLoader),this._container.get(p.TrustedNameContextLoader),this._container.get(d.NftContextLoader),this._container.get(l.TokenContextLoader),this._container.get(i.TransactionContextLoader),this._container.get(x.UniswapContextLoader)]}_getDefaultTypedDataLoader(){return this._container.get(m.TypedDataContextLoader)}_getWeb3CheckLoader(){return this._container.get(c.Web3CheckContextLoader)}_getSolanaLoader(){try{return this._container.get(C.SolanaContextLoader)}catch{return{load:async e=>n(new Error("[ContextModule] - DefaultContextModule: no SolanaContextLoader bound"))}}}async getContexts(e){const o=this._loaders.map(t=>t.load(e));return(await Promise.all(o)).flat()}async getContext(e){const o=this._loaders.filter(t=>t.loadField).map(t=>t.loadField(e));return(await Promise.all(o)).find(t=>t!==null)||{type:r.ERROR,error:new Error(`Field type not supported: ${e.type}`)}}async getTypedDataFilters(e){return this._typedDataLoader.load(e)}async getWeb3Checks(e){return(await this._web3CheckLoader.load(e)).caseOf({Right:a=>({type:r.WEB3_CHECK,payload:a.descriptor,certificate:a.certificate}),Left:()=>null})}async getSolanaContext(e){return await this._solanaLoader.load(e)}}export{P as DefaultContextModule};
1
+ import{Left as n}from"purify-ts";import{dynamicNetworkTypes as i}from"./dynamic-network/di/dynamicNetworkTypes";import{transactionTypes as p}from"./transaction/di/transactionTypes";import{trustedNameTypes as d}from"./trusted-name/di/trustedNameTypes";import{externalPluginTypes as s}from"./external-plugin/di/externalPluginTypes";import{nftTypes as C}from"./nft/di/nftTypes";import{ClearSignContextType as r}from"./shared/model/ClearSignContext";import{solanaContextTypes as m}from"./solana/di/solanaContextTypes";import{tokenTypes as l}from"./token/di/tokenTypes";import{typedDataTypes as c}from"./typed-data/di/typedDataTypes";import{uniswapTypes as x}from"./uniswap/di/uniswapTypes";import{web3CheckTypes as y}from"./web3-check/di/web3CheckTypes";import{makeContainer as L}from"./di";class E{_container;_loaders;_typedDataLoader;_web3CheckLoader;_solanaLoader;constructor(t){this._container=L({config:t}),this._loaders=t.defaultLoaders?this._getDefaultLoaders():[],this._loaders.push(...t.customLoaders),this._typedDataLoader=t.customTypedDataLoader??this._getDefaultTypedDataLoader(),this._web3CheckLoader=t.customWeb3CheckLoader??this._getWeb3CheckLoader(),this._solanaLoader=t.customSolanaLoader??this._getSolanaLoader()}_getDefaultLoaders(){return[this._container.get(s.ExternalPluginContextLoader),this._container.get(d.TrustedNameContextLoader),this._container.get(C.NftContextLoader),this._container.get(l.TokenContextLoader),this._container.get(p.TransactionContextLoader),this._container.get(x.UniswapContextLoader),this._container.get(i.DynamicNetworkContextLoader)]}_getDefaultTypedDataLoader(){return this._container.get(c.TypedDataContextLoader)}_getWeb3CheckLoader(){return this._container.get(y.Web3CheckContextLoader)}_getSolanaLoader(){try{return this._container.get(m.SolanaContextLoader)}catch{return{load:async t=>n(new Error("[ContextModule] - DefaultContextModule: no SolanaContextLoader bound"))}}}async getContexts(t){const o=this._loaders.map(e=>e.load(t));return(await Promise.all(o)).flat()}async getContext(t){const o=this._loaders.filter(e=>e.loadField).map(e=>e.loadField(t));return(await Promise.all(o)).find(e=>e!==null)||{type:r.ERROR,error:new Error(`Field type not supported: ${t.type}`)}}async getTypedDataFilters(t){return this._typedDataLoader.load(t)}async getWeb3Checks(t){return(await this._web3CheckLoader.load(t)).caseOf({Right:a=>({type:r.WEB3_CHECK,payload:a.descriptor,certificate:a.certificate}),Left:()=>null})}async getSolanaContext(t){return await this._solanaLoader.load(t)}}export{E as DefaultContextModule};
2
2
  //# sourceMappingURL=DefaultContextModule.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/DefaultContextModule.ts"],
4
- "sourcesContent": ["import { type Container } from \"inversify\";\nimport { Left } from \"purify-ts\";\n\nimport type { TypedDataClearSignContext } from \"@/shared/model/TypedDataClearSignContext\";\nimport type { TypedDataContext } from \"@/shared/model/TypedDataContext\";\nimport { transactionTypes } from \"@/transaction/di/transactionTypes\";\nimport { trustedNameTypes } from \"@/trusted-name/di/trustedNameTypes\";\n\nimport { type ContextModuleConfig } from \"./config/model/ContextModuleConfig\";\nimport { externalPluginTypes } from \"./external-plugin/di/externalPluginTypes\";\nimport { type ExternalPluginContextLoader } from \"./external-plugin/domain/ExternalPluginContextLoader\";\nimport { nftTypes } from \"./nft/di/nftTypes\";\nimport { type NftContextLoader } from \"./nft/domain/NftContextLoader\";\nimport { type ContextLoader } from \"./shared/domain/ContextLoader\";\nimport {\n type ClearSignContext,\n type ClearSignContextSuccess,\n ClearSignContextType,\n} from \"./shared/model/ClearSignContext\";\nimport { type SolanaTransactionContext } from \"./shared/model/SolanaTransactionContext\";\nimport {\n type TransactionContext,\n type TransactionFieldContext,\n} from \"./shared/model/TransactionContext\";\nimport { solanaContextTypes } from \"./solana/di/solanaContextTypes\";\nimport { type SolanaContextLoader } from \"./solana/domain/SolanaContextLoader\";\nimport { type SolanaTransactionContextResult } from \"./solana/domain/solanaContextTypes\";\nimport { tokenTypes } from \"./token/di/tokenTypes\";\nimport { type TokenContextLoader } from \"./token/domain/TokenContextLoader\";\nimport { type TransactionContextLoader } from \"./transaction/domain/TransactionContextLoader\";\nimport { type TrustedNameContextLoader } from \"./trusted-name/domain/TrustedNameContextLoader\";\nimport { typedDataTypes } from \"./typed-data/di/typedDataTypes\";\nimport type { TypedDataContextLoader } from \"./typed-data/domain/TypedDataContextLoader\";\nimport { uniswapTypes } from \"./uniswap/di/uniswapTypes\";\nimport { type UniswapContextLoader } from \"./uniswap/domain/UniswapContextLoader\";\nimport { web3CheckTypes } from \"./web3-check/di/web3CheckTypes\";\nimport { type Web3CheckContextLoader } from \"./web3-check/domain/Web3CheckContextLoader\";\nimport {\n type Web3CheckContext,\n type Web3Checks,\n} from \"./web3-check/domain/web3CheckTypes\";\nimport { type ContextModule } from \"./ContextModule\";\nimport { makeContainer } from \"./di\";\n\nexport class DefaultContextModule implements ContextModule {\n private _container: Container;\n private _loaders: ContextLoader[];\n private _typedDataLoader: TypedDataContextLoader;\n private _web3CheckLoader: Web3CheckContextLoader;\n private _solanaLoader: SolanaContextLoader;\n\n constructor(args: ContextModuleConfig) {\n this._container = makeContainer({ config: args });\n this._loaders = args.defaultLoaders ? this._getDefaultLoaders() : [];\n this._loaders.push(...args.customLoaders);\n this._typedDataLoader =\n args.customTypedDataLoader ?? this._getDefaultTypedDataLoader();\n this._web3CheckLoader =\n args.customWeb3CheckLoader ?? this._getWeb3CheckLoader();\n this._solanaLoader = args.customSolanaLoader ?? this._getSolanaLoader();\n }\n\n private _getDefaultLoaders(): ContextLoader[] {\n return [\n this._container.get<ExternalPluginContextLoader>(\n externalPluginTypes.ExternalPluginContextLoader,\n ),\n this._container.get<TrustedNameContextLoader>(\n trustedNameTypes.TrustedNameContextLoader,\n ),\n this._container.get<NftContextLoader>(nftTypes.NftContextLoader),\n this._container.get<TokenContextLoader>(tokenTypes.TokenContextLoader),\n this._container.get<TransactionContextLoader>(\n transactionTypes.TransactionContextLoader,\n ),\n this._container.get<UniswapContextLoader>(\n uniswapTypes.UniswapContextLoader,\n ),\n ];\n }\n\n private _getDefaultTypedDataLoader(): TypedDataContextLoader {\n return this._container.get<TypedDataContextLoader>(\n typedDataTypes.TypedDataContextLoader,\n );\n }\n\n private _getWeb3CheckLoader(): Web3CheckContextLoader {\n return this._container.get<Web3CheckContextLoader>(\n web3CheckTypes.Web3CheckContextLoader,\n );\n }\n\n private _getSolanaLoader(): SolanaContextLoader {\n try {\n return this._container.get<SolanaContextLoader>(\n solanaContextTypes.SolanaContextLoader,\n );\n } catch {\n return {\n load: async (_ctx) =>\n Left(\n new Error(\n \"[ContextModule] - DefaultContextModule: no SolanaContextLoader bound\",\n ),\n ),\n };\n }\n }\n\n public async getContexts(\n transaction: TransactionContext,\n ): Promise<ClearSignContext[]> {\n const promises = this._loaders.map((fetcher) => fetcher.load(transaction));\n const responses = await Promise.all(promises);\n return responses.flat();\n }\n\n public async getContext(\n field: TransactionFieldContext,\n ): Promise<ClearSignContext> {\n const promises = this._loaders\n .filter((fetcher) => fetcher.loadField)\n .map((fetcher) => fetcher.loadField!(field));\n const responses = await Promise.all(promises);\n return (\n responses.find((resp) => resp !== null) || {\n type: ClearSignContextType.ERROR,\n error: new Error(`Field type not supported: ${field.type}`),\n }\n );\n }\n\n public async getTypedDataFilters(\n typedData: TypedDataContext,\n ): Promise<TypedDataClearSignContext> {\n return this._typedDataLoader.load(typedData);\n }\n\n public async getWeb3Checks(\n transactionContext: Web3CheckContext,\n ): Promise<ClearSignContextSuccess<ClearSignContextType.WEB3_CHECK> | null> {\n const web3Checks = await this._web3CheckLoader.load(transactionContext);\n\n return web3Checks.caseOf({\n Right: (checks: Web3Checks) => ({\n type: ClearSignContextType.WEB3_CHECK,\n payload: checks.descriptor,\n certificate: checks.certificate,\n }),\n Left: () => null,\n });\n }\n\n public async getSolanaContext(\n transactionContext: SolanaTransactionContext,\n ): Promise<SolanaTransactionContextResult> {\n return await this._solanaLoader.load(transactionContext);\n }\n}\n"],
5
- "mappings": "AACA,OAAS,QAAAA,MAAY,YAIrB,OAAS,oBAAAC,MAAwB,oCACjC,OAAS,oBAAAC,MAAwB,qCAGjC,OAAS,uBAAAC,MAA2B,2CAEpC,OAAS,YAAAC,MAAgB,oB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W,CAAC,EAEzE,OADkB,MAAM,QAAQ,IAAIC,CAAQ,GAC3B,KAAK,CACxB,CAEA,MAAa,WACXE,EAC2B,CAC3B,MAAMF,EAAW,KAAK,SACnB,OAAQC,GAAYA,EAAQ,SAAS,EACrC,IAAKA,GAAYA,EAAQ,UAAWC,CAAK,CAAC,EAE7C,OADkB,MAAM,QAAQ,IAAIF,CAAQ,GAEhC,KAAMG,GAASA,IAAS,IAAI,GAAK,CACzC,KAAMd,EAAqB,MAC3B,MAAO,IAAI,MAAM,6BAA6Ba,EAAM,IAAI,EAAE,CAC5D,CAEJ,CAEA,MAAa,oBACXE,EACoC,CACpC,OAAO,KAAK,iBAAiB,KAAKA,CAAS,CAC7C,CAEA,MAAa,cACXC,EAC0E,CAG1E,OAFmB,MAAM,KAAK,iBAAiB,KAAKA,CAAkB,GAEpD,OAAO,CACvB,MAAQC,IAAwB,CAC9B,KAAMjB,EAAqB,WAC3B,QAASiB,EAAO,WAChB,YAAaA,EAAO,WACtB,GACA,KAAM,IAAM,IACd,CAAC,CACH,CAEA,MAAa,iBACXD,EACyC,CACzC,OAAO,MAAM,KAAK,cAAc,KAAKA,CAAkB,CACzD,CACF",
6
- "names": ["Left", "transactionTypes", "trustedNameTypes", "externalPluginTypes", "nftTypes", "ClearSignContextType", "solanaContextTypes", "tokenTypes", "typedDataTypes", "uniswapTypes", "web3CheckTypes", "makeContainer", "DefaultContextModule", "args", "_ctx", "transaction", "promises", "fetcher", "field", "resp", "typedData", "transactionContext", "checks"]
4
+ "sourcesContent": ["import { type Container } from \"inversify\";\nimport { Left } from \"purify-ts\";\n\nimport { dynamicNetworkTypes } from \"@/dynamic-network/di/dynamicNetworkTypes\";\nimport { type DynamicNetworkContextLoader } from \"@/dynamic-network/domain/DynamicNetworkContextLoader\";\nimport type { TypedDataClearSignContext } from \"@/shared/model/TypedDataClearSignContext\";\nimport type { TypedDataContext } from \"@/shared/model/TypedDataContext\";\nimport { transactionTypes } from \"@/transaction/di/transactionTypes\";\nimport { trustedNameTypes } from \"@/trusted-name/di/trustedNameTypes\";\n\nimport { type ContextModuleConfig } from \"./config/model/ContextModuleConfig\";\nimport { externalPluginTypes } from \"./external-plugin/di/externalPluginTypes\";\nimport { type ExternalPluginContextLoader } from \"./external-plugin/domain/ExternalPluginContextLoader\";\nimport { nftTypes } from \"./nft/di/nftTypes\";\nimport { type NftContextLoader } from \"./nft/domain/NftContextLoader\";\nimport { type ContextLoader } from \"./shared/domain/ContextLoader\";\nimport {\n type ClearSignContext,\n type ClearSignContextSuccess,\n ClearSignContextType,\n} from \"./shared/model/ClearSignContext\";\nimport { type SolanaTransactionContext } from \"./shared/model/SolanaTransactionContext\";\nimport {\n type TransactionContext,\n type TransactionFieldContext,\n} from \"./shared/model/TransactionContext\";\nimport { solanaContextTypes } from \"./solana/di/solanaContextTypes\";\nimport { type SolanaContextLoader } from \"./solana/domain/SolanaContextLoader\";\nimport { type SolanaTransactionContextResult } from \"./solana/domain/solanaContextTypes\";\nimport { tokenTypes } from \"./token/di/tokenTypes\";\nimport { type TokenContextLoader } from \"./token/domain/TokenContextLoader\";\nimport { type TransactionContextLoader } from \"./transaction/domain/TransactionContextLoader\";\nimport { type TrustedNameContextLoader } from \"./trusted-name/domain/TrustedNameContextLoader\";\nimport { typedDataTypes } from \"./typed-data/di/typedDataTypes\";\nimport type { TypedDataContextLoader } from \"./typed-data/domain/TypedDataContextLoader\";\nimport { uniswapTypes } from \"./uniswap/di/uniswapTypes\";\nimport { type UniswapContextLoader } from \"./uniswap/domain/UniswapContextLoader\";\nimport { web3CheckTypes } from \"./web3-check/di/web3CheckTypes\";\nimport { type Web3CheckContextLoader } from \"./web3-check/domain/Web3CheckContextLoader\";\nimport {\n type Web3CheckContext,\n type Web3Checks,\n} from \"./web3-check/domain/web3CheckTypes\";\nimport { type ContextModule } from \"./ContextModule\";\nimport { makeContainer } from \"./di\";\n\nexport class DefaultContextModule implements ContextModule {\n private _container: Container;\n private _loaders: ContextLoader[];\n private _typedDataLoader: TypedDataContextLoader;\n private _web3CheckLoader: Web3CheckContextLoader;\n private _solanaLoader: SolanaContextLoader;\n\n constructor(args: ContextModuleConfig) {\n this._container = makeContainer({ config: args });\n this._loaders = args.defaultLoaders ? this._getDefaultLoaders() : [];\n this._loaders.push(...args.customLoaders);\n this._typedDataLoader =\n args.customTypedDataLoader ?? this._getDefaultTypedDataLoader();\n this._web3CheckLoader =\n args.customWeb3CheckLoader ?? this._getWeb3CheckLoader();\n this._solanaLoader = args.customSolanaLoader ?? this._getSolanaLoader();\n }\n\n private _getDefaultLoaders(): ContextLoader[] {\n return [\n this._container.get<ExternalPluginContextLoader>(\n externalPluginTypes.ExternalPluginContextLoader,\n ),\n this._container.get<TrustedNameContextLoader>(\n trustedNameTypes.TrustedNameContextLoader,\n ),\n this._container.get<NftContextLoader>(nftTypes.NftContextLoader),\n this._container.get<TokenContextLoader>(tokenTypes.TokenContextLoader),\n this._container.get<TransactionContextLoader>(\n transactionTypes.TransactionContextLoader,\n ),\n this._container.get<UniswapContextLoader>(\n uniswapTypes.UniswapContextLoader,\n ),\n this._container.get<DynamicNetworkContextLoader>(\n dynamicNetworkTypes.DynamicNetworkContextLoader,\n ),\n ];\n }\n\n private _getDefaultTypedDataLoader(): TypedDataContextLoader {\n return this._container.get<TypedDataContextLoader>(\n typedDataTypes.TypedDataContextLoader,\n );\n }\n\n private _getWeb3CheckLoader(): Web3CheckContextLoader {\n return this._container.get<Web3CheckContextLoader>(\n web3CheckTypes.Web3CheckContextLoader,\n );\n }\n\n private _getSolanaLoader(): SolanaContextLoader {\n try {\n return this._container.get<SolanaContextLoader>(\n solanaContextTypes.SolanaContextLoader,\n );\n } catch {\n return {\n load: async (_ctx) =>\n Left(\n new Error(\n \"[ContextModule] - DefaultContextModule: no SolanaContextLoader bound\",\n ),\n ),\n };\n }\n }\n\n public async getContexts(\n transaction: TransactionContext,\n ): Promise<ClearSignContext[]> {\n const promises = this._loaders.map((fetcher) => fetcher.load(transaction));\n const responses = await Promise.all(promises);\n return responses.flat();\n }\n\n public async getContext(\n field: TransactionFieldContext,\n ): Promise<ClearSignContext> {\n const promises = this._loaders\n .filter((fetcher) => fetcher.loadField)\n .map((fetcher) => fetcher.loadField!(field));\n const responses = await Promise.all(promises);\n return (\n responses.find((resp) => resp !== null) || {\n type: ClearSignContextType.ERROR,\n error: new Error(`Field type not supported: ${field.type}`),\n }\n );\n }\n\n public async getTypedDataFilters(\n typedData: TypedDataContext,\n ): Promise<TypedDataClearSignContext> {\n return this._typedDataLoader.load(typedData);\n }\n\n public async getWeb3Checks(\n transactionContext: Web3CheckContext,\n ): Promise<ClearSignContextSuccess<ClearSignContextType.WEB3_CHECK> | null> {\n const web3Checks = await this._web3CheckLoader.load(transactionContext);\n\n return web3Checks.caseOf({\n Right: (checks: Web3Checks) => ({\n type: ClearSignContextType.WEB3_CHECK,\n payload: checks.descriptor,\n certificate: checks.certificate,\n }),\n Left: () => null,\n });\n }\n\n public async getSolanaContext(\n transactionContext: SolanaTransactionContext,\n ): Promise<SolanaTransactionContextResult> {\n return await this._solanaLoader.load(transactionContext);\n }\n}\n"],
5
+ "mappings": "AACA,OAAS,QAAAA,MAAY,YAErB,OAAS,uBAAAC,MAA2B,2CAIpC,OAAS,oBAAAC,MAAwB,oCACjC,OAAS,oBAAAC,MAAwB,qCAGjC,OAAS,uBAAAC,MAA2B,2CAEpC,OAAS,YAAAC,MAAgB,oBAGzB,OAGE,wBAAAC,MACK,kCAMP,OAAS,sBAAAC,MAA0B,iCAGnC,OAAS,cAAAC,MAAkB,wBAI3B,OAAS,kBAAAC,MAAsB,iCAE/B,OAAS,gBAAAC,MAAoB,4BAE7B,OAAS,kBAAAC,MAAsB,iCAO/B,OAAS,iBAAAC,MAAqB,OAEvB,MAAMC,CAA8C,CACjD,WACA,SACA,iBACA,iBACA,cAER,YAAYC,EAA2B,CACrC,KAAK,WAAaF,EAAc,CAAE,OAAQE,CAAK,CAAC,EAChD,KAAK,SAAWA,EAAK,eAAiB,KAAK,m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AM,6BAA6Ba,EAAM,IAAI,EAAE,CAC5D,CAEJ,CAEA,MAAa,oBACXE,EACoC,CACpC,OAAO,KAAK,iBAAiB,KAAKA,CAAS,CAC7C,CAEA,MAAa,cACXC,EAC0E,CAG1E,OAFmB,MAAM,KAAK,iBAAiB,KAAKA,CAAkB,GAEpD,OAAO,CACvB,MAAQC,IAAwB,CAC9B,KAAMjB,EAAqB,WAC3B,QAASiB,EAAO,WAChB,YAAaA,EAAO,WACtB,GACA,KAAM,IAAM,IACd,CAAC,CACH,CAEA,MAAa,iBACXD,EACyC,CACzC,OAAO,MAAM,KAAK,cAAc,KAAKA,CAAkB,CACzD,CACF",
6
+ "names": ["Left", "dynamicNetworkTypes", "transactionTypes", "trustedNameTypes", "externalPluginTypes", "nftTypes", "ClearSignContextType", "solanaContextTypes", "tokenTypes", "typedDataTypes", "uniswapTypes", "web3CheckTypes", "makeContainer", "DefaultContextModule", "args", "_ctx", "transaction", "promises", "fetcher", "field", "resp", "typedData", "transactionContext", "checks"]
7
7
  }
@@ -1,2 +1,2 @@
1
- import{DeviceModelId as c}from"@ledgerhq/device-management-kit";import{Left as r,Right as i}from"purify-ts";import{DefaultContextModule as a}from"./DefaultContextModule";const d=()=>({load:vi.fn(),loadField:vi.fn()});describe("DefaultContextModule",()=>{const s={load:vi.fn()},o={customLoaders:[],defaultLoaders:!1,customTypedDataLoader:s,cal:{url:"https://cal/v1",mode:"prod",branch:"main"},web3checks:{url:"https://web3checks/v3"},metadataService:{url:"https://metadata/v2"},originToken:"originToken"};beforeEach(()=>{vi.restoreAllMocks()}),it("should initialize the context module with all the default loaders",async()=>{const t=await new a(o).getContexts({});expect(t).toEqual([])}),it("should return an empty array when no loaders",async()=>{const t=await new a(o).getContexts({});expect(t).toEqual([])}),it("should call all fetch method from metadata fetcher",async()=>{const e=d();await new a({...o,customLoaders:[e,e]}).getContexts({}),expect(e.load).toHaveBeenCalledTimes(2)}),it("should return an array of context response",async()=>{const e=d(),t=[[{type:"provideERC20Info",payload:"payload1"}],[{type:"provideERC20Info",payload:"payload2"},{type:"plugin",payload:"payload3"}]];vi.spyOn(e,"load").mockResolvedValueOnce(t[0]).mockResolvedValueOnce(t[1]);const l=await new a({...o,customLoaders:[e,e]}).getContexts({});expect(e.load).toHaveBeenCalledTimes(2),expect(l).toEqual(t.flat())}),it("should call the typed data loader",async()=>{await new a({...o,customTypedDataLoader:s}).getTypedDataFilters({}),expect(s.load).toHaveBeenCalledTimes(1)}),it("should return a single context",async()=>{const e=d(),t=[null,{type:"token",payload:"payload"}];vi.spyOn(e,"loadField").mockResolvedValueOnce(t[0]).mockResolvedValueOnce(t[1]);const l=await new a({...o,customLoaders:[e,{load:vi.fn()},e]}).getContext({type:"token"});expect(e.loadField).toHaveBeenCalledTimes(2),expect(l).toEqual({type:"token",payload:"payload"})}),it("should return a web3 check context",async()=>{const e=d();vi.spyOn(e,"load").mockResolvedValueOnce(i({descriptor:"payload"}));const n=await new a({...o,customLoaders:[],customWeb3CheckLoader:e}).getWeb3Checks({deviceModelId:c.FLEX,from:"from",rawTx:"rawTx",chainId:1});expect(e.load).toHaveBeenCalledTimes(1),expect(n).toEqual({type:"web3Check",payload:"payload"})}),it("should return null if no web3 check context",async()=>{const e=d();vi.spyOn(e,"load").mockResolvedValue(r(new Error("error")));const n=await new a({...o,customLoaders:[],customWeb3CheckLoader:e}).getWeb3Checks({deviceModelId:c.FLEX,from:"from",rawTx:"rawTx",chainId:1});expect(e.load).toHaveBeenCalledTimes(1),expect(n).toBeNull()}),it("context field not supported",async()=>{const e=d(),t=[null,null];vi.spyOn(e,"loadField").mockResolvedValueOnce(t[0]).mockResolvedValueOnce(t[1]);const l=await new a({...o,customLoaders:[e,{load:vi.fn()},e]}).getContext({type:"token"});expect(e.loadField).toHaveBeenCalledTimes(2),expect(l).toEqual({type:"error",error:new Error("Field type not supported: token")})}),it("getField not implemented",async()=>{const t=await new a({...o,customLoaders:[{load:vi.fn()}]}).getContext({type:"token"});expect(t).toEqual({type:"error",error:new Error("Field type not supported: token")})}),it("should throw an error if origin token is not provided",()=>{expect(()=>new a({...o,originToken:void 0})).toThrow("Origin token is required")})});
1
+ import{DeviceModelId as c}from"@ledgerhq/device-management-kit";import{Left as r,Right as i}from"purify-ts";import{DefaultContextModule as a}from"./DefaultContextModule";const d=()=>({load:vi.fn(),loadField:vi.fn()});describe("DefaultContextModule",()=>{const s={load:vi.fn()},o={customLoaders:[],defaultLoaders:!1,customTypedDataLoader:s,cal:{url:"https://cal/v1",mode:"prod",branch:"main"},web3checks:{url:"https://web3checks/v3"},metadataServiceDomain:{url:"https://metadata.com"},originToken:"originToken"};beforeEach(()=>{vi.restoreAllMocks()}),it("should initialize the context module with all the default loaders",async()=>{const t=await new a(o).getContexts({});expect(t).toEqual([])}),it("should return an empty array when no loaders",async()=>{const t=await new a(o).getContexts({});expect(t).toEqual([])}),it("should call all fetch method from metadata fetcher",async()=>{const e=d();await new a({...o,customLoaders:[e,e]}).getContexts({}),expect(e.load).toHaveBeenCalledTimes(2)}),it("should return an array of context response",async()=>{const e=d(),t=[[{type:"provideERC20Info",payload:"payload1"}],[{type:"provideERC20Info",payload:"payload2"},{type:"plugin",payload:"payload3"}]];vi.spyOn(e,"load").mockResolvedValueOnce(t[0]).mockResolvedValueOnce(t[1]);const l=await new a({...o,customLoaders:[e,e]}).getContexts({});expect(e.load).toHaveBeenCalledTimes(2),expect(l).toEqual(t.flat())}),it("should call the typed data loader",async()=>{await new a({...o,customTypedDataLoader:s}).getTypedDataFilters({}),expect(s.load).toHaveBeenCalledTimes(1)}),it("should return a single context",async()=>{const e=d(),t=[null,{type:"token",payload:"payload"}];vi.spyOn(e,"loadField").mockResolvedValueOnce(t[0]).mockResolvedValueOnce(t[1]);const l=await new a({...o,customLoaders:[e,{load:vi.fn()},e]}).getContext({type:"token"});expect(e.loadField).toHaveBeenCalledTimes(2),expect(l).toEqual({type:"token",payload:"payload"})}),it("should return a web3 check context",async()=>{const e=d();vi.spyOn(e,"load").mockResolvedValueOnce(i({descriptor:"payload"}));const n=await new a({...o,customLoaders:[],customWeb3CheckLoader:e}).getWeb3Checks({deviceModelId:c.FLEX,from:"from",rawTx:"rawTx",chainId:1});expect(e.load).toHaveBeenCalledTimes(1),expect(n).toEqual({type:"web3Check",payload:"payload"})}),it("should return null if no web3 check context",async()=>{const e=d();vi.spyOn(e,"load").mockResolvedValue(r(new Error("error")));const n=await new a({...o,customLoaders:[],customWeb3CheckLoader:e}).getWeb3Checks({deviceModelId:c.FLEX,from:"from",rawTx:"rawTx",chainId:1});expect(e.load).toHaveBeenCalledTimes(1),expect(n).toBeNull()}),it("context field not supported",async()=>{const e=d(),t=[null,null];vi.spyOn(e,"loadField").mockResolvedValueOnce(t[0]).mockResolvedValueOnce(t[1]);const l=await new a({...o,customLoaders:[e,{load:vi.fn()},e]}).getContext({type:"token"});expect(e.loadField).toHaveBeenCalledTimes(2),expect(l).toEqual({type:"error",error:new Error("Field type not supported: token")})}),it("getField not implemented",async()=>{const t=await new a({...o,customLoaders:[{load:vi.fn()}]}).getContext({type:"token"});expect(t).toEqual({type:"error",error:new Error("Field type not supported: token")})}),it("should throw an error if origin token is not provided",()=>{expect(()=>new a({...o,originToken:void 0})).toThrow("Origin token is required")})});
2
2
  //# sourceMappingURL=DefaultContextModule.test.js.map