@ledgerhq/context-module 0.0.0-develop-20260918001351 → 0.0.0-develop-20260920001530
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.
- package/lib/cjs/package.json +1 -1
- package/lib/cjs/src/modules/multichain/reporter/model/BlindSigningEvent.js +1 -1
- package/lib/cjs/src/modules/multichain/reporter/model/BlindSigningEvent.js.map +2 -2
- package/lib/cjs/src/modules/solana/instruction-info/data/HttpInstructionInfoDataSource.test.js +1 -1
- package/lib/cjs/src/modules/solana/instruction-info/data/HttpInstructionInfoDataSource.test.js.map +2 -2
- package/lib/cjs/src/modules/solana/instruction-info/data/InstructionInfoDto.js +1 -1
- package/lib/cjs/src/modules/solana/instruction-info/data/InstructionInfoDto.js.map +3 -3
- package/lib/cjs/src/modules/solana/instruction-info/data/InstructionInfoMapper.js +1 -1
- package/lib/cjs/src/modules/solana/instruction-info/data/InstructionInfoMapper.js.map +3 -3
- package/lib/cjs/src/modules/solana/instruction-info/data/InstructionInfoMapper.test.js +1 -1
- package/lib/cjs/src/modules/solana/instruction-info/data/InstructionInfoMapper.test.js.map +2 -2
- package/lib/cjs/src/modules/solana/model/SolanaClearSignContext.js +1 -1
- package/lib/cjs/src/modules/solana/model/SolanaClearSignContext.js.map +2 -2
- package/lib/cjs/src/modules/solana/model/SolanaPayloads.js +1 -1
- package/lib/cjs/src/modules/solana/model/SolanaPayloads.js.map +2 -2
- package/lib/cjs/src/modules/solana/token-account-state/data/HttpTokenAccountStateDataSource.js +1 -1
- package/lib/cjs/src/modules/solana/token-account-state/data/HttpTokenAccountStateDataSource.js.map +3 -3
- package/lib/cjs/src/modules/solana/token-account-state/data/HttpTokenAccountStateDataSource.test.js +1 -1
- package/lib/cjs/src/modules/solana/token-account-state/data/HttpTokenAccountStateDataSource.test.js.map +3 -3
- package/lib/esm/package.json +1 -1
- package/lib/esm/src/modules/multichain/reporter/model/BlindSigningEvent.js +1 -1
- package/lib/esm/src/modules/multichain/reporter/model/BlindSigningEvent.js.map +2 -2
- package/lib/esm/src/modules/solana/instruction-info/data/HttpInstructionInfoDataSource.test.js +1 -1
- package/lib/esm/src/modules/solana/instruction-info/data/HttpInstructionInfoDataSource.test.js.map +2 -2
- package/lib/esm/src/modules/solana/instruction-info/data/InstructionInfoDto.js +1 -1
- package/lib/esm/src/modules/solana/instruction-info/data/InstructionInfoDto.js.map +3 -3
- package/lib/esm/src/modules/solana/instruction-info/data/InstructionInfoMapper.js +1 -1
- package/lib/esm/src/modules/solana/instruction-info/data/InstructionInfoMapper.js.map +3 -3
- package/lib/esm/src/modules/solana/instruction-info/data/InstructionInfoMapper.test.js +1 -1
- package/lib/esm/src/modules/solana/instruction-info/data/InstructionInfoMapper.test.js.map +3 -3
- package/lib/esm/src/modules/solana/model/SolanaClearSignContext.js +1 -1
- package/lib/esm/src/modules/solana/model/SolanaClearSignContext.js.map +2 -2
- package/lib/esm/src/modules/solana/model/SolanaPayloads.js.map +2 -2
- package/lib/esm/src/modules/solana/token-account-state/data/HttpTokenAccountStateDataSource.js +1 -1
- package/lib/esm/src/modules/solana/token-account-state/data/HttpTokenAccountStateDataSource.js.map +3 -3
- package/lib/esm/src/modules/solana/token-account-state/data/HttpTokenAccountStateDataSource.test.js +1 -1
- package/lib/esm/src/modules/solana/token-account-state/data/HttpTokenAccountStateDataSource.test.js.map +3 -3
- package/lib/types/src/modules/multichain/reporter/model/BlindSigningEvent.d.ts +1 -0
- package/lib/types/src/modules/multichain/reporter/model/BlindSigningEvent.d.ts.map +1 -1
- package/lib/types/src/modules/solana/instruction-info/data/InstructionInfoDto.d.ts +27 -0
- package/lib/types/src/modules/solana/instruction-info/data/InstructionInfoDto.d.ts.map +1 -1
- package/lib/types/src/modules/solana/instruction-info/data/InstructionInfoMapper.d.ts +3 -2
- package/lib/types/src/modules/solana/instruction-info/data/InstructionInfoMapper.d.ts.map +1 -1
- package/lib/types/src/modules/solana/model/SolanaClearSignContext.d.ts +1 -1
- package/lib/types/src/modules/solana/model/SolanaClearSignContext.d.ts.map +1 -1
- package/lib/types/src/modules/solana/model/SolanaPayloads.d.ts +15 -0
- package/lib/types/src/modules/solana/model/SolanaPayloads.d.ts.map +1 -1
- package/lib/types/src/modules/solana/token-account-state/data/HttpTokenAccountStateDataSource.d.ts +3 -2
- package/lib/types/src/modules/solana/token-account-state/data/HttpTokenAccountStateDataSource.d.ts.map +1 -1
- package/lib/types/tsconfig.prod.tsbuildinfo +1 -1
- package/package.json +5 -5
package/lib/cjs/src/modules/solana/token-account-state/data/HttpTokenAccountStateDataSource.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var p=Object.defineProperty;var
|
|
1
|
+
"use strict";var p=Object.defineProperty;var m=Object.getOwnPropertyDescriptor;var h=Object.getOwnPropertyNames;var y=Object.prototype.hasOwnProperty;var T=(n,e)=>{for(var o in e)p(n,o,{get:e[o],enumerable:!0})},w=(n,e,o,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of h(e))!y.call(n,t)&&t!==o&&p(n,t,{get:()=>e[t],enumerable:!(r=m(e,t))||r.enumerable});return n};var b=n=>w(p({},"__esModule",{value:!0}),n),d=(n,e,o,r)=>{for(var t=r>1?void 0:r?m(e,o):e,i=n.length-1,c;i>=0;i--)(c=n[i])&&(t=(r?c(e,o,t):c(t))||t);return r&&t&&p(e,o,t),t},l=(n,e)=>(o,r)=>e(o,r,n);var v={};T(v,{HttpTokenAccountStateDataSource:()=>g});module.exports=b(v);var a=require("inversify"),s=require("purify-ts"),u=require("../../../../config/di/configTypes"),f=require("../../../../shared/network/di/networkTypes"),k=require("../../../../shared/utils/HexStringUtils"),S=require("../../../../shared/utils/signedDescriptorDto");let g=class{constructor(e,o,r){this.config=e;this.http=r;this.logger=o("HttpTokenAccountStateDataSource")}logger;async getTokenAccountState({tokenAccount:e,challenge:o}){let r;try{r=await this.http.get(`${this.config.metadataServiceDomain.url}/v2/solana/token-account-state/${e}`,{params:{challenge:o}})}catch(t){const i=t instanceof Error?t.message:String(t);return(0,s.Left)(new Error(`[ContextModule] HttpTokenAccountStateDataSource: Failed to fetch token account state: ${i}`))}return S.signedDescriptorDtoCodec.decode(r).caseOf({Left:t=>(0,s.Left)(new Error(`[ContextModule] HttpTokenAccountStateDataSource: malformed response for ${e}: ${t}`)),Right:t=>{r.owner!==void 0&&r.mint===void 0&&this.logger.warn("[getTokenAccountState] response has owner but no mint \u2014 canonical-ATA check will fail and the OWNER binding will be dropped by the device",{data:{tokenAccount:e}});let i;try{i=k.HexStringUtils.hexToBytes(t.signedDescriptor)}catch(c){return(0,s.Left)(new Error(`[ContextModule] HttpTokenAccountStateDataSource: invalid hex in signedDescriptor for ${e}: ${c.message}`))}return r.nativePreBalance===void 0&&this.logger.debug("[getTokenAccountState] nativePreBalance absent in response \u2014 native resets will not attest wrappable excess",{data:{tokenAccount:e}}),(0,s.Right)({tokenAccount:e,descriptor:i,mint:r.mint,keyId:t.keyId,keyUsage:t.keyUsage})}})}};g=d([(0,a.injectable)(),l(0,(0,a.inject)(u.configTypes.Config)),l(1,(0,a.inject)(u.configTypes.ContextModuleLoggerFactory)),l(2,(0,a.inject)(f.networkTypes.NetworkClient))],g);0&&(module.exports={HttpTokenAccountStateDataSource});
|
|
2
2
|
//# sourceMappingURL=HttpTokenAccountStateDataSource.js.map
|
package/lib/cjs/src/modules/solana/token-account-state/data/HttpTokenAccountStateDataSource.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../../src/modules/solana/token-account-state/data/HttpTokenAccountStateDataSource.ts"],
|
|
4
|
-
"sourcesContent": ["import {
|
|
5
|
-
"mappings": "okBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,qCAAAE,IAAA,eAAAC,EAAAH,
|
|
6
|
-
"names": ["HttpTokenAccountStateDataSource_exports", "__export", "HttpTokenAccountStateDataSource", "__toCommonJS", "import_inversify", "import_purify_ts", "import_configTypes", "import_networkTypes", "import_HexStringUtils", "import_signedDescriptorDto", "HttpTokenAccountStateDataSource", "config", "http", "tokenAccount", "challenge", "dto", "error", "reason", "validated", "descriptor", "__decorateClass", "__decorateParam"]
|
|
4
|
+
"sourcesContent": ["import {\n DmkNetworkClient,\n LoggerPublisherService,\n} from \"@ledgerhq/device-management-kit\";\nimport { inject, injectable } from \"inversify\";\nimport { Either, Left, Right } from \"purify-ts\";\n\nimport { configTypes } from \"@/config/di/configTypes\";\nimport { type ContextModuleServiceConfig } from \"@/config/model/ContextModuleConfig\";\nimport { networkTypes } from \"@/shared/network/di/networkTypes\";\nimport { HexStringUtils } from \"@/shared/utils/HexStringUtils\";\nimport { signedDescriptorDtoCodec } from \"@/shared/utils/signedDescriptorDto\";\n\nimport {\n type GetTokenAccountStateParams,\n type TokenAccountStateDataSource,\n type TokenAccountStateResult,\n} from \"./TokenAccountStateDataSource\";\n\ntype TokenAccountStateResponseDto = {\n descriptorType?: string;\n descriptorVersion?: number;\n tokenAccount?: string;\n mint?: string;\n owner?: string;\n preBalance?: number;\n nativePreBalance?: number; // wrappable lamport excess; absent = old backend\n signedDescriptor: string;\n keyId: string;\n keyUsage: string;\n};\n\n@injectable()\nexport class HttpTokenAccountStateDataSource\n implements TokenAccountStateDataSource\n{\n private logger: LoggerPublisherService;\n\n constructor(\n @inject(configTypes.Config)\n private readonly config: ContextModuleServiceConfig,\n @inject(configTypes.ContextModuleLoggerFactory)\n loggerFactory: (tag: string) => LoggerPublisherService,\n @inject(networkTypes.NetworkClient)\n private readonly http: DmkNetworkClient,\n ) {\n this.logger = loggerFactory(\"HttpTokenAccountStateDataSource\");\n }\n\n public async getTokenAccountState({\n tokenAccount,\n challenge,\n }: GetTokenAccountStateParams): Promise<\n Either<Error, TokenAccountStateResult>\n > {\n let dto: TokenAccountStateResponseDto;\n try {\n dto = (await this.http.get(\n `${this.config.metadataServiceDomain.url}/v2/solana/token-account-state/${tokenAccount}`,\n { params: { challenge } },\n )) as TokenAccountStateResponseDto;\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n return Left(\n new Error(\n `[ContextModule] HttpTokenAccountStateDataSource: Failed to fetch token account state: ${reason}`,\n ),\n );\n }\n\n return signedDescriptorDtoCodec\n .decode(dto)\n .caseOf<Either<Error, TokenAccountStateResult>>({\n Left: (error) =>\n Left(\n new Error(\n `[ContextModule] HttpTokenAccountStateDataSource: malformed response for ${tokenAccount}: ${error}`,\n ),\n ),\n Right: (validated) => {\n if (dto.owner !== undefined && dto.mint === undefined) {\n this.logger.warn(\n \"[getTokenAccountState] response has owner but no mint \u2014 \" +\n \"canonical-ATA check will fail and the OWNER binding will be dropped by the device\",\n { data: { tokenAccount } },\n );\n }\n\n let descriptor: Uint8Array;\n try {\n descriptor = HexStringUtils.hexToBytes(validated.signedDescriptor);\n } catch (error) {\n return Left(\n new Error(\n `[ContextModule] HttpTokenAccountStateDataSource: invalid hex in signedDescriptor for ${tokenAccount}: ${(error as Error).message}`,\n ),\n );\n }\n\n if (dto.nativePreBalance === undefined) {\n this.logger.debug(\n \"[getTokenAccountState] nativePreBalance absent in response \u2014 native resets will not attest wrappable excess\",\n { data: { tokenAccount } },\n );\n }\n\n return Right({\n tokenAccount,\n descriptor,\n mint: dto.mint,\n keyId: validated.keyId,\n keyUsage: validated.keyUsage,\n });\n },\n });\n }\n}\n"],
|
|
5
|
+
"mappings": "okBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,qCAAAE,IAAA,eAAAC,EAAAH,GAIA,IAAAI,EAAmC,qBACnCC,EAAoC,qBAEpCC,EAA4B,mCAE5BC,EAA6B,4CAC7BC,EAA+B,yCAC/BC,EAAyC,8CAsBlC,IAAMC,EAAN,KAEP,CAGE,YAEmBC,EAEjBC,EAEiBC,EACjB,CALiB,YAAAF,EAIA,UAAAE,EAEjB,KAAK,OAASD,EAAc,iCAAiC,CAC/D,CAXQ,OAaR,MAAa,qBAAqB,CAChC,aAAAE,EACA,UAAAC,CACF,EAEE,CACA,IAAIC,EACJ,GAAI,CACFA,EAAO,MAAM,KAAK,KAAK,IACrB,GAAG,KAAK,OAAO,sBAAsB,GAAG,kCAAkCF,CAAY,GACtF,CAAE,OAAQ,CAAE,UAAAC,CAAU,CAAE,CAC1B,CACF,OAASE,EAAO,CACd,MAAMC,EAASD,aAAiB,MAAQA,EAAM,QAAU,OAAOA,CAAK,EACpE,SAAO,QACL,IAAI,MACF,yFAAyFC,CAAM,EACjG,CACF,CACF,CAEA,OAAO,2BACJ,OAAOF,CAAG,EACV,OAA+C,CAC9C,KAAOC,MACL,QACE,IAAI,MACF,2EAA2EH,CAAY,KAAKG,CAAK,EACnG,CACF,EACF,MAAQE,GAAc,CAChBH,EAAI,QAAU,QAAaA,EAAI,OAAS,QAC1C,KAAK,OAAO,KACV,iJAEA,CAAE,KAAM,CAAE,aAAAF,CAAa,CAAE,CAC3B,EAGF,IAAIM,EACJ,GAAI,CACFA,EAAa,iBAAe,WAAWD,EAAU,gBAAgB,CACnE,OAASF,EAAO,CACd,SAAO,QACL,IAAI,MACF,wFAAwFH,CAAY,KAAMG,EAAgB,OAAO,EACnI,CACF,CACF,CAEA,OAAID,EAAI,mBAAqB,QAC3B,KAAK,OAAO,MACV,mHACA,CAAE,KAAM,CAAE,aAAAF,CAAa,CAAE,CAC3B,KAGK,SAAM,CACX,aAAAA,EACA,WAAAM,EACA,KAAMJ,EAAI,KACV,MAAOG,EAAU,MACjB,SAAUA,EAAU,QACtB,CAAC,CACH,CACF,CAAC,CACL,CACF,EAnFaT,EAANW,EAAA,IADN,cAAW,EAOPC,EAAA,eAAO,cAAY,MAAM,GAEzBA,EAAA,eAAO,cAAY,0BAA0B,GAE7CA,EAAA,eAAO,eAAa,aAAa,IAVzBZ",
|
|
6
|
+
"names": ["HttpTokenAccountStateDataSource_exports", "__export", "HttpTokenAccountStateDataSource", "__toCommonJS", "import_inversify", "import_purify_ts", "import_configTypes", "import_networkTypes", "import_HexStringUtils", "import_signedDescriptorDto", "HttpTokenAccountStateDataSource", "config", "loggerFactory", "http", "tokenAccount", "challenge", "dto", "error", "reason", "validated", "descriptor", "__decorateClass", "__decorateParam"]
|
|
7
7
|
}
|
package/lib/cjs/src/modules/solana/token-account-state/data/HttpTokenAccountStateDataSource.test.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var c=require("purify-ts"),e=require("vitest"),s=require("./HttpTokenAccountStateDataSource");const X={debug:e.vi.fn(),info:e.vi.fn(),warn:e.vi.fn(),error:e.vi.fn(),subscribers:[]},d=()=>X;(0,e.describe)("HttpTokenAccountStateDataSource",()=>{let o,n;const t="TokenAccountAddrXXXXXXXXXXXXXXXXXXXXXXXXXXX",a="deadbeef",i={metadataServiceDomain:{url:"https://nft.api.ledger.com"}};(0,e.beforeEach)(()=>{e.vi.clearAllMocks(),n={get:e.vi.fn()},o=new s.HttpTokenAccountStateDataSource(i,d,n)}),(0,e.it)("calls the metadata endpoint with the challenge param",async()=>{n.get.mockResolvedValue({descriptorType:"token_account_state",signedDescriptor:"01020304",keyId:"tas_key",keyUsage:"coin_meta"}),await o.getTokenAccountState({tokenAccount:t,challenge:a}),(0,e.expect)(n.get).toHaveBeenCalledWith(`https://nft.api.ledger.com/v2/solana/token-account-state/${t}`,{params:{challenge:a}})}),(0,e.it)("decodes signedDescriptor hex into Uint8Array",async()=>{n.get.mockResolvedValue({signedDescriptor:"deadbeef",keyId:"k",keyUsage:"u"});const r=await o.getTokenAccountState({tokenAccount:t,challenge:a});(0,e.expect)(r).toEqual((0,c.Right)({tokenAccount:t,descriptor:new Uint8Array([222,173,190,239]),keyId:"k",keyUsage:"u"}))}),(0,e.it)("returns Left on malformed response (missing signedDescriptor)",async()=>{n.get.mockResolvedValue({keyId:"k",keyUsage:"u"});const r=await o.getTokenAccountState({tokenAccount:t,challenge:a});(0,e.expect)(r.isLeft()).toBe(!0),(0,e.expect)(r.extract().message).toMatch(new RegExp(String.raw`\[ContextModule\] HttpTokenAccountStateDataSource: malformed response for ${t}:`))}),(0,e.it)("returns Left when signedDescriptor is not valid hex",async()=>{n.get.mockResolvedValue({signedDescriptor:"ZZZZ",keyId:"k",keyUsage:"u"});const r=await o.getTokenAccountState({tokenAccount:t,challenge:a});(0,e.expect)(r.isLeft()).toBe(!0),(0,e.expect)(r.extract().message).toMatch(/invalid hex/)}),(0,e.it)("returns Left when HTTP client throws",async()=>{n.get.mockRejectedValue(new Error("net"));const r=await o.getTokenAccountState({tokenAccount:t,challenge:a});(0,e.expect)(r).toEqual((0,c.Left)(new Error("[ContextModule] HttpTokenAccountStateDataSource: Failed to fetch token account state: net")))}),(0,e.it)("logs debug when nativePreBalance is absent",async()=>{n.get.mockResolvedValue({signedDescriptor:"deadbeef",keyId:"k",keyUsage:"u"}),await o.getTokenAccountState({tokenAccount:t,challenge:a}),(0,e.expect)(X.debug).toHaveBeenCalledWith(e.expect.stringContaining("nativePreBalance absent"),e.expect.objectContaining({data:{tokenAccount:t}}))}),(0,e.it)("does not log debug when nativePreBalance is present",async()=>{n.get.mockResolvedValue({signedDescriptor:"deadbeef",keyId:"k",keyUsage:"u",nativePreBalance:1e3}),await o.getTokenAccountState({tokenAccount:t,challenge:a}),(0,e.expect)(X.debug).not.toHaveBeenCalled()}),(0,e.it)("logs warn when owner is present but mint is absent",async()=>{n.get.mockResolvedValue({signedDescriptor:"deadbeef",keyId:"k",keyUsage:"u",owner:"OwnerPubkeyXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"}),await o.getTokenAccountState({tokenAccount:t,challenge:a}),(0,e.expect)(X.warn).toHaveBeenCalledWith(e.expect.stringContaining("owner but no mint"),e.expect.objectContaining({data:{tokenAccount:t}}))}),(0,e.it)("does not log warn when both owner and mint are present",async()=>{n.get.mockResolvedValue({signedDescriptor:"deadbeef",keyId:"k",keyUsage:"u",owner:"OwnerPubkeyXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",mint:"MintPubkeyXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"}),await o.getTokenAccountState({tokenAccount:t,challenge:a}),(0,e.expect)(X.warn).not.toHaveBeenCalled()})});
|
|
2
2
|
//# sourceMappingURL=HttpTokenAccountStateDataSource.test.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../../src/modules/solana/token-account-state/data/HttpTokenAccountStateDataSource.test.ts"],
|
|
4
|
-
"sourcesContent": ["import { type DmkNetworkClient } from \"@ledgerhq/device-management-kit\";\nimport { Left, Right } from \"purify-ts\";\nimport { beforeEach, describe, expect, it, vi } from \"vitest\";\n\nimport { type ContextModuleServiceConfig } from \"@/config/model/ContextModuleConfig\";\n\nimport { HttpTokenAccountStateDataSource } from \"./HttpTokenAccountStateDataSource\";\nimport { type TokenAccountStateDataSource } from \"./TokenAccountStateDataSource\";\n\ndescribe(\"HttpTokenAccountStateDataSource\", () => {\n let datasource: TokenAccountStateDataSource;\n let httpMock: { get: ReturnType<typeof vi.fn> };\n const tokenAccount = \"TokenAccountAddrXXXXXXXXXXXXXXXXXXXXXXXXXXX\";\n const challenge = \"deadbeef\";\n const config: ContextModuleServiceConfig = {\n metadataServiceDomain: { url: \"https://nft.api.ledger.com\" },\n } as ContextModuleServiceConfig;\n\n beforeEach(() => {\n vi.clearAllMocks();\n httpMock = { get: vi.fn() };\n datasource = new HttpTokenAccountStateDataSource(\n config,\n httpMock as unknown as DmkNetworkClient,\n );\n });\n\n it(\"calls the metadata endpoint with the challenge param\", async () => {\n httpMock.get.mockResolvedValue({\n descriptorType: \"token_account_state\",\n signedDescriptor: \"01020304\",\n keyId: \"tas_key\",\n keyUsage: \"coin_meta\",\n });\n\n await datasource.getTokenAccountState({ tokenAccount, challenge });\n\n expect(httpMock.get).toHaveBeenCalledWith(\n `https://nft.api.ledger.com/v2/solana/token-account-state/${tokenAccount}`,\n { params: { challenge } },\n );\n });\n\n it(\"decodes signedDescriptor hex into Uint8Array\", async () => {\n httpMock.get.mockResolvedValue({\n signedDescriptor: \"deadbeef\",\n keyId: \"k\",\n keyUsage: \"u\",\n });\n\n const result = await datasource.getTokenAccountState({\n tokenAccount,\n challenge,\n });\n\n expect(result).toEqual(\n Right({\n tokenAccount,\n descriptor: new Uint8Array([0xde, 0xad, 0xbe, 0xef]),\n keyId: \"k\",\n keyUsage: \"u\",\n }),\n );\n });\n\n it(\"returns Left on malformed response (missing signedDescriptor)\", async () => {\n httpMock.get.mockResolvedValue({ keyId: \"k\", keyUsage: \"u\" });\n\n const result = await datasource.getTokenAccountState({\n tokenAccount,\n challenge,\n });\n\n expect(result.isLeft()).toBe(true);\n expect((result.extract() as Error).message).toMatch(\n new RegExp(\n String.raw`\\[ContextModule\\] HttpTokenAccountStateDataSource: malformed response for ${tokenAccount}:`,\n ),\n );\n });\n\n it(\"returns Left when signedDescriptor is not valid hex\", async () => {\n httpMock.get.mockResolvedValue({\n signedDescriptor: \"ZZZZ\",\n keyId: \"k\",\n keyUsage: \"u\",\n });\n\n const result = await datasource.getTokenAccountState({\n tokenAccount,\n challenge,\n });\n\n expect(result.isLeft()).toBe(true);\n expect((result.extract() as Error).message).toMatch(/invalid hex/);\n });\n\n it(\"returns Left when HTTP client throws\", async () => {\n httpMock.get.mockRejectedValue(new Error(\"net\"));\n\n const result = await datasource.getTokenAccountState({\n tokenAccount,\n challenge,\n });\n\n expect(result).toEqual(\n Left(\n new Error(\n \"[ContextModule] HttpTokenAccountStateDataSource: Failed to fetch token account state: net\",\n ),\n ),\n );\n });\n});\n"],
|
|
5
|
-
"mappings": "aACA,IAAAA,EAA4B,qBAC5BC,EAAqD,kBAIrDC,EAAgD,
|
|
6
|
-
"names": ["import_purify_ts", "import_vitest", "import_HttpTokenAccountStateDataSource", "datasource", "httpMock", "tokenAccount", "challenge", "config", "result"]
|
|
4
|
+
"sourcesContent": ["import { type DmkNetworkClient } from \"@ledgerhq/device-management-kit\";\nimport { Left, Right } from \"purify-ts\";\nimport { beforeEach, describe, expect, it, vi } from \"vitest\";\n\nimport { type ContextModuleServiceConfig } from \"@/config/model/ContextModuleConfig\";\n\nimport { HttpTokenAccountStateDataSource } from \"./HttpTokenAccountStateDataSource\";\nimport { type TokenAccountStateDataSource } from \"./TokenAccountStateDataSource\";\n\nconst mockLogger = {\n debug: vi.fn(),\n info: vi.fn(),\n warn: vi.fn(),\n error: vi.fn(),\n subscribers: [],\n};\nconst mockLoggerFactory = () => mockLogger;\n\ndescribe(\"HttpTokenAccountStateDataSource\", () => {\n let datasource: TokenAccountStateDataSource;\n let httpMock: { get: ReturnType<typeof vi.fn> };\n const tokenAccount = \"TokenAccountAddrXXXXXXXXXXXXXXXXXXXXXXXXXXX\";\n const challenge = \"deadbeef\";\n const config: ContextModuleServiceConfig = {\n metadataServiceDomain: { url: \"https://nft.api.ledger.com\" },\n } as ContextModuleServiceConfig;\n\n beforeEach(() => {\n vi.clearAllMocks();\n httpMock = { get: vi.fn() };\n datasource = new HttpTokenAccountStateDataSource(\n config,\n mockLoggerFactory,\n httpMock as unknown as DmkNetworkClient,\n );\n });\n\n it(\"calls the metadata endpoint with the challenge param\", async () => {\n httpMock.get.mockResolvedValue({\n descriptorType: \"token_account_state\",\n signedDescriptor: \"01020304\",\n keyId: \"tas_key\",\n keyUsage: \"coin_meta\",\n });\n\n await datasource.getTokenAccountState({ tokenAccount, challenge });\n\n expect(httpMock.get).toHaveBeenCalledWith(\n `https://nft.api.ledger.com/v2/solana/token-account-state/${tokenAccount}`,\n { params: { challenge } },\n );\n });\n\n it(\"decodes signedDescriptor hex into Uint8Array\", async () => {\n httpMock.get.mockResolvedValue({\n signedDescriptor: \"deadbeef\",\n keyId: \"k\",\n keyUsage: \"u\",\n });\n\n const result = await datasource.getTokenAccountState({\n tokenAccount,\n challenge,\n });\n\n expect(result).toEqual(\n Right({\n tokenAccount,\n descriptor: new Uint8Array([0xde, 0xad, 0xbe, 0xef]),\n keyId: \"k\",\n keyUsage: \"u\",\n }),\n );\n });\n\n it(\"returns Left on malformed response (missing signedDescriptor)\", async () => {\n httpMock.get.mockResolvedValue({ keyId: \"k\", keyUsage: \"u\" });\n\n const result = await datasource.getTokenAccountState({\n tokenAccount,\n challenge,\n });\n\n expect(result.isLeft()).toBe(true);\n expect((result.extract() as Error).message).toMatch(\n new RegExp(\n String.raw`\\[ContextModule\\] HttpTokenAccountStateDataSource: malformed response for ${tokenAccount}:`,\n ),\n );\n });\n\n it(\"returns Left when signedDescriptor is not valid hex\", async () => {\n httpMock.get.mockResolvedValue({\n signedDescriptor: \"ZZZZ\",\n keyId: \"k\",\n keyUsage: \"u\",\n });\n\n const result = await datasource.getTokenAccountState({\n tokenAccount,\n challenge,\n });\n\n expect(result.isLeft()).toBe(true);\n expect((result.extract() as Error).message).toMatch(/invalid hex/);\n });\n\n it(\"returns Left when HTTP client throws\", async () => {\n httpMock.get.mockRejectedValue(new Error(\"net\"));\n\n const result = await datasource.getTokenAccountState({\n tokenAccount,\n challenge,\n });\n\n expect(result).toEqual(\n Left(\n new Error(\n \"[ContextModule] HttpTokenAccountStateDataSource: Failed to fetch token account state: net\",\n ),\n ),\n );\n });\n\n it(\"logs debug when nativePreBalance is absent\", async () => {\n httpMock.get.mockResolvedValue({\n signedDescriptor: \"deadbeef\",\n keyId: \"k\",\n keyUsage: \"u\",\n });\n\n await datasource.getTokenAccountState({ tokenAccount, challenge });\n\n expect(mockLogger.debug).toHaveBeenCalledWith(\n expect.stringContaining(\"nativePreBalance absent\"),\n expect.objectContaining({ data: { tokenAccount } }),\n );\n });\n\n it(\"does not log debug when nativePreBalance is present\", async () => {\n httpMock.get.mockResolvedValue({\n signedDescriptor: \"deadbeef\",\n keyId: \"k\",\n keyUsage: \"u\",\n nativePreBalance: 1000,\n });\n\n await datasource.getTokenAccountState({ tokenAccount, challenge });\n\n expect(mockLogger.debug).not.toHaveBeenCalled();\n });\n\n it(\"logs warn when owner is present but mint is absent\", async () => {\n httpMock.get.mockResolvedValue({\n signedDescriptor: \"deadbeef\",\n keyId: \"k\",\n keyUsage: \"u\",\n owner: \"OwnerPubkeyXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\",\n });\n\n await datasource.getTokenAccountState({ tokenAccount, challenge });\n\n expect(mockLogger.warn).toHaveBeenCalledWith(\n expect.stringContaining(\"owner but no mint\"),\n expect.objectContaining({ data: { tokenAccount } }),\n );\n });\n\n it(\"does not log warn when both owner and mint are present\", async () => {\n httpMock.get.mockResolvedValue({\n signedDescriptor: \"deadbeef\",\n keyId: \"k\",\n keyUsage: \"u\",\n owner: \"OwnerPubkeyXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\",\n mint: \"MintPubkeyXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\",\n });\n\n await datasource.getTokenAccountState({ tokenAccount, challenge });\n\n expect(mockLogger.warn).not.toHaveBeenCalled();\n });\n});\n"],
|
|
5
|
+
"mappings": "aACA,IAAAA,EAA4B,qBAC5BC,EAAqD,kBAIrDC,EAAgD,6CAGhD,MAAMC,EAAa,CACjB,MAAO,KAAG,GAAG,EACb,KAAM,KAAG,GAAG,EACZ,KAAM,KAAG,GAAG,EACZ,MAAO,KAAG,GAAG,EACb,YAAa,CAAC,CAChB,EACMC,EAAoB,IAAMD,KAEhC,YAAS,kCAAmC,IAAM,CAChD,IAAIE,EACAC,EACJ,MAAMC,EAAe,8CACfC,EAAY,WACZC,EAAqC,CACzC,sBAAuB,CAAE,IAAK,4BAA6B,CAC7D,KAEA,cAAW,IAAM,CACf,KAAG,cAAc,EACjBH,EAAW,CAAE,IAAK,KAAG,GAAG,CAAE,EAC1BD,EAAa,IAAI,kCACfI,EACAL,EACAE,CACF,CACF,CAAC,KAED,MAAG,uDAAwD,SAAY,CACrEA,EAAS,IAAI,kBAAkB,CAC7B,eAAgB,sBAChB,iBAAkB,WAClB,MAAO,UACP,SAAU,WACZ,CAAC,EAED,MAAMD,EAAW,qBAAqB,CAAE,aAAAE,EAAc,UAAAC,CAAU,CAAC,KAEjE,UAAOF,EAAS,GA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StateDataSource", "mockLogger", "mockLoggerFactory", "datasource", "httpMock", "tokenAccount", "challenge", "config", "result"]
|
|
7
7
|
}
|
package/lib/esm/package.json
CHANGED
|
@@ -58,5 +58,5 @@
|
|
|
58
58
|
"watch:builds": "pnpm ldmk-tool watch --entryPoints index.ts,src/**/*.ts --tsconfig tsconfig.prod.json",
|
|
59
59
|
"watch:types": "concurrently \"tsc --watch -p tsconfig.prod.json\" \"tsc-alias --watch -p tsconfig.prod.json\""
|
|
60
60
|
},
|
|
61
|
-
"version": "0.0.0-develop-
|
|
61
|
+
"version": "0.0.0-develop-20260920001530"
|
|
62
62
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=Object.freeze({ETH_SIGN_TRANSACTION:"eth_signTransaction",ETH_SIGN_TYPED_DATA:"eth_signTypedData"}),n=Object.freeze({NO_CLEAR_SIGNING_CONTEXT:"no_clear_signing_context",DEVICE_REJECTED_CONTEXT:"device_rejected_context",UNRECOGNIZED_PROGRAM:"unrecognized_program"}),
|
|
1
|
+
const e=Object.freeze({ETH_SIGN_TRANSACTION:"eth_signTransaction",ETH_SIGN_TYPED_DATA:"eth_signTypedData"}),n=Object.freeze({NO_CLEAR_SIGNING_CONTEXT:"no_clear_signing_context",DEVICE_REJECTED_CONTEXT:"device_rejected_context",UNRECOGNIZED_PROGRAM:"unrecognized_program",STALE_DESCRIPTOR:"stale_descriptor"}),t=Object.freeze({BASIC:"basic",EIP7730:"eip7730"}),i=Object.freeze({DESKTOP:"desktop",MOBILE:"mobile"});export{n as BlindSignReason,e as BlindSigningMethod,i as BlindSigningPlatform,t as ClearSigningType};
|
|
2
2
|
//# sourceMappingURL=BlindSigningEvent.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../../src/modules/multichain/reporter/model/BlindSigningEvent.ts"],
|
|
4
|
-
"sourcesContent": ["export const BlindSigningMethod = Object.freeze({\n ETH_SIGN_TRANSACTION: \"eth_signTransaction\",\n ETH_SIGN_TYPED_DATA: \"eth_signTypedData\",\n} as const);\nexport type BlindSigningMethod =\n (typeof BlindSigningMethod)[keyof typeof BlindSigningMethod];\n\nexport const BlindSignReason = Object.freeze({\n NO_CLEAR_SIGNING_CONTEXT: \"no_clear_signing_context\",\n DEVICE_REJECTED_CONTEXT: \"device_rejected_context\",\n UNRECOGNIZED_PROGRAM: \"unrecognized_program\",\n} as const);\nexport type BlindSignReason =\n (typeof BlindSignReason)[keyof typeof BlindSignReason];\n\nexport const ClearSigningType = Object.freeze({\n BASIC: \"basic\",\n EIP7730: \"eip7730\",\n} as const);\nexport type ClearSigningType =\n (typeof ClearSigningType)[keyof typeof ClearSigningType];\n\nexport const BlindSigningPlatform = Object.freeze({\n DESKTOP: \"desktop\",\n MOBILE: \"mobile\",\n} as const);\nexport type BlindSigningPlatform =\n (typeof BlindSigningPlatform)[keyof typeof BlindSigningPlatform];\n"],
|
|
5
|
-
"mappings": "AAAO,MAAMA,EAAqB,OAAO,OAAO,CAC9C,qBAAsB,sBACtB,oBAAqB,mBACvB,CAAU,EAIGC,EAAkB,OAAO,OAAO,CAC3C,yBAA0B,2BAC1B,wBAAyB,0BACzB,qBAAsB,
|
|
4
|
+
"sourcesContent": ["export const BlindSigningMethod = Object.freeze({\n ETH_SIGN_TRANSACTION: \"eth_signTransaction\",\n ETH_SIGN_TYPED_DATA: \"eth_signTypedData\",\n} as const);\nexport type BlindSigningMethod =\n (typeof BlindSigningMethod)[keyof typeof BlindSigningMethod];\n\nexport const BlindSignReason = Object.freeze({\n NO_CLEAR_SIGNING_CONTEXT: \"no_clear_signing_context\",\n DEVICE_REJECTED_CONTEXT: \"device_rejected_context\",\n UNRECOGNIZED_PROGRAM: \"unrecognized_program\",\n STALE_DESCRIPTOR: \"stale_descriptor\",\n} as const);\nexport type BlindSignReason =\n (typeof BlindSignReason)[keyof typeof BlindSignReason];\n\nexport const ClearSigningType = Object.freeze({\n BASIC: \"basic\",\n EIP7730: \"eip7730\",\n} as const);\nexport type ClearSigningType =\n (typeof ClearSigningType)[keyof typeof ClearSigningType];\n\nexport const BlindSigningPlatform = Object.freeze({\n DESKTOP: \"desktop\",\n MOBILE: \"mobile\",\n} as const);\nexport type BlindSigningPlatform =\n (typeof BlindSigningPlatform)[keyof typeof BlindSigningPlatform];\n"],
|
|
5
|
+
"mappings": "AAAO,MAAMA,EAAqB,OAAO,OAAO,CAC9C,qBAAsB,sBACtB,oBAAqB,mBACvB,CAAU,EAIGC,EAAkB,OAAO,OAAO,CAC3C,yBAA0B,2BAC1B,wBAAyB,0BACzB,qBAAsB,uBACtB,iBAAkB,kBACpB,CAAU,EAIGC,EAAmB,OAAO,OAAO,CAC5C,MAAO,QACP,QAAS,SACX,CAAU,EAIGC,EAAuB,OAAO,OAAO,CAChD,QAAS,UACT,OAAQ,QACV,CAAU",
|
|
6
6
|
"names": ["BlindSigningMethod", "BlindSignReason", "ClearSigningType", "BlindSigningPlatform"]
|
|
7
7
|
}
|
package/lib/esm/src/modules/solana/instruction-info/data/HttpInstructionInfoDataSource.test.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Left as
|
|
1
|
+
import{Left as d,Right as l}from"purify-ts";import{beforeEach as g,describe as h,expect as e,it as s,vi as p}from"vitest";import{SolanaTransactionScanChainId as i}from"../../../../modules/solana/model/SolanaTransactionScanChainId";import{HttpInstructionInfoDataSource as f}from"./HttpInstructionInfoDataSource";h("HttpInstructionInfoDataSource",()=>{let r,n;const t="11111111111111111111111111111111",a="solana-mainnet",m={cal:{url:"https://global.api.prd.ledger.com/cal/v1",mode:"prod",branch:"main"}},u=[{id:t,chain_id:i.MAINNET,instructions:[{discriminator_hex:"00000000",instruction_name:"createAccount",descriptor:{data:"00010101",signatures:{prod:"prodsig",test:"testsig"}},display_fields:[],value_flow_ports:[],hide_rules:[],account_resets:[]}]}];g(()=>{p.clearAllMocks(),n={get:p.fn()},r=new f(m,n)}),s("calls CAL /solana_programs with id, chain_id and output params",async()=>{n.get.mockResolvedValue(u),await r.getInstructionInfo({programId:t,network:a}),e(n.get).toHaveBeenCalledTimes(1),e(n.get).toHaveBeenCalledWith("https://global.api.prd.ledger.com/cal/v1/solana_programs",{params:{id:t,chain_id:i.MAINNET,output:"id,chain_id,instructions",ref:"branch:main"}})}),s("maps devnet/testnet networks to their numeric chain ids",async()=>{n.get.mockResolvedValue(u),await r.getInstructionInfo({programId:t,network:"solana-devnet"}),e(n.get).toHaveBeenCalledWith("https://global.api.prd.ledger.com/cal/v1/solana_programs",e.objectContaining({params:e.objectContaining({chain_id:901})}))}),s("returns Right with each descriptor transformed into the core payload on success",async()=>{n.get.mockResolvedValue(u);const o=await r.getInstructionInfo({programId:t,network:a});e(o).toEqual(l({programId:t,descriptors:{"00000000":l({programId:t,discriminator:"00000000",instructionName:"createAccount",instructionInfo:{data:"00010101",signature:"prodsig"},substructures:[],enumVariants:[],idlDescriptor:{typePool:[],rootType:0},mintAssociations:[],ownerAssociations:[],valueFlowPorts:[],accountResets:[],displayFields:[],hideRules:[]})},enumVariants:[]}))}),s("keys a descriptor without `discriminator_hex` under the empty string",async()=>{n.get.mockResolvedValue([{id:t,chain_id:i.MAINNET,instructions:[{instruction_name:"addMemo",descriptor:{data:"00010101",signatures:{prod:"prodsig",test:"testsig"}}}]}]);const o=await r.getInstructionInfo({programId:t,network:a});e(o.isRight()).toBe(!0);const{descriptors:c}=o.unsafeCoerce();e(Object.keys(c)).toEqual([""]),e(c[""].unsafeCoerce()).toEqual(e.objectContaining({programId:t,discriminator:"",instructionInfo:{data:"00010101",signature:"prodsig"}}))}),s("returns Left when the response array is empty",async()=>{n.get.mockResolvedValue([]);const o=await r.getInstructionInfo({programId:t,network:a});e(o).toEqual(d(new Error(`[ContextModule] HttpInstructionInfoDataSource: empty response for program ${t}`)))}),s("returns Left when no program object matches the requested programId",async()=>{n.get.mockResolvedValue([{id:"OtherProgram",chain_id:i.MAINNET,instructions:[]}]);const o=await r.getInstructionInfo({programId:t,network:a});e(o).toEqual(d(new Error(`[ContextModule] HttpInstructionInfoDataSource: no descriptors for program ${t}`)))}),s("returns Left (not a throw) when an instruction descriptor is malformed",async()=>{n.get.mockResolvedValue([{id:t,chain_id:i.MAINNET,instructions:[{discriminator_hex:"00000000"}]}]);const o=await r.getInstructionInfo({programId:t,network:a});e(o.isLeft()).toBe(!0),e(o.extract().message).toMatch(new RegExp(String.raw`\[ContextModule\] HttpInstructionInfoDataSource: malformed descriptors for program ${t}:`))}),s("returns Left (not a throw) when account_schema.slots is not an array",async()=>{n.get.mockResolvedValue([{id:t,chain_id:i.MAINNET,instructions:[{discriminator_hex:"00000000",descriptor:{data:"00010101",signatures:{prod:"prodsig",test:"testsig"}},account_schema:{slots:{}}}]}]);const o=await r.getInstructionInfo({programId:t,network:a});e(o.isLeft()).toBe(!0),e(o.extract().message).toMatch(new RegExp(String.raw`\[ContextModule\] HttpInstructionInfoDataSource: malformed descriptors for program ${t}:`))}),s("returns Right with accountSchema mapped through when it is well-formed",async()=>{n.get.mockResolvedValue([{id:t,chain_id:i.MAINNET,instructions:[{discriminator_hex:"00000000",descriptor:{data:"00010101",signatures:{prod:"prodsig",test:"testsig"}},account_schema:{count_min:2,count_max:2,slots:[{signer:"REQUIRED",writable:"EITHER"}]}}]}]);const o=await r.getInstructionInfo({programId:t,network:a});e(o.isRight()).toBe(!0);const{descriptors:c}=o.unsafeCoerce();e(c["00000000"].unsafeCoerce()).toEqual(e.objectContaining({accountSchema:{count_min:2,count_max:2,remaining_policy:{signer:"EITHER",writable:"EITHER"},slots:[{signer:"REQUIRED",writable:"EITHER"}]}}))}),s("returns Left when the HTTP client throws",async()=>{n.get.mockRejectedValue(new Error("network"));const o=await r.getInstructionInfo({programId:t,network:a});e(o).toEqual(d(new Error("[ContextModule] HttpInstructionInfoDataSource: Failed to fetch instruction descriptors: network")))})});
|
|
2
2
|
//# sourceMappingURL=HttpInstructionInfoDataSource.test.js.map
|
package/lib/esm/src/modules/solana/instruction-info/data/HttpInstructionInfoDataSource.test.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../../src/modules/solana/instruction-info/data/HttpInstructionInfoDataSource.test.ts"],
|
|
4
|
-
"sourcesContent": ["import { type DmkNetworkClient } from \"@ledgerhq/device-management-kit\";\nimport { Left, Right } from \"purify-ts\";\nimport { beforeEach, describe, expect, it, vi } from \"vitest\";\n\nimport { type ContextModuleServiceConfig } from \"@/config/model/ContextModuleConfig\";\nimport { SolanaTransactionScanChainId } from \"@/modules/solana/model/SolanaTransactionScanChainId\";\n\nimport { HttpInstructionInfoDataSource } from \"./HttpInstructionInfoDataSource\";\nimport { type InstructionInfoDataSource } from \"./InstructionInfoDataSource\";\nimport { type CalInstructionInfoResponseDto } from \"./InstructionInfoDto\";\n\ndescribe(\"HttpInstructionInfoDataSource\", () => {\n let datasource: InstructionInfoDataSource;\n let httpMock: { get: ReturnType<typeof vi.fn> };\n const programId = \"11111111111111111111111111111111\";\n const network = \"solana-mainnet\";\n const config: ContextModuleServiceConfig = {\n cal: {\n url: \"https://global.api.prd.ledger.com/cal/v1\",\n mode: \"prod\",\n branch: \"main\",\n },\n } as ContextModuleServiceConfig;\n\n const successResponse: CalInstructionInfoResponseDto = [\n {\n id: programId,\n chain_id: SolanaTransactionScanChainId.MAINNET,\n instructions: [\n {\n discriminator_hex: \"00000000\",\n instruction_name: \"createAccount\",\n descriptor: {\n data: \"00010101\",\n signatures: { prod: \"prodsig\", test: \"testsig\" },\n },\n display_fields: [],\n value_flow_ports: [],\n hide_rules: [],\n account_resets: [],\n },\n ],\n },\n ];\n\n beforeEach(() => {\n vi.clearAllMocks();\n httpMock = { get: vi.fn() };\n datasource = new HttpInstructionInfoDataSource(\n config,\n httpMock as unknown as DmkNetworkClient,\n );\n });\n\n it(\"calls CAL /solana_programs with id, chain_id and output params\", async () => {\n httpMock.get.mockResolvedValue(successResponse);\n\n await datasource.getInstructionInfo({ programId, network });\n\n expect(httpMock.get).toHaveBeenCalledTimes(1);\n expect(httpMock.get).toHaveBeenCalledWith(\n \"https://global.api.prd.ledger.com/cal/v1/solana_programs\",\n {\n params: {\n id: programId,\n chain_id: SolanaTransactionScanChainId.MAINNET,\n output: \"id,chain_id,instructions\",\n ref: \"branch:main\",\n },\n },\n );\n });\n\n it(\"maps devnet/testnet networks to their numeric chain ids\", async () => {\n httpMock.get.mockResolvedValue(successResponse);\n\n await datasource.getInstructionInfo({\n programId,\n network: \"solana-devnet\",\n });\n\n expect(httpMock.get).toHaveBeenCalledWith(\n \"https://global.api.prd.ledger.com/cal/v1/solana_programs\",\n expect.objectContaining({\n params: expect.objectContaining({ chain_id: 901 }),\n }),\n );\n });\n\n it(\"returns Right with each descriptor transformed into the core payload on success\", async () => {\n httpMock.get.mockResolvedValue(successResponse);\n\n const result = await datasource.getInstructionInfo({ programId, network });\n\n expect(result).toEqual(\n Right({\n programId,\n descriptors: {\n \"00000000\": Right({\n programId,\n discriminator: \"00000000\",\n instructionName: \"createAccount\",\n instructionInfo: { data: \"00010101\", signature: \"prodsig\" },\n substructures: [],\n enumVariants: [],\n idlDescriptor: { typePool: [], rootType: 0 },\n mintAssociations: [],\n ownerAssociations: [],\n valueFlowPorts: [],\n accountResets: [],\n displayFields: [],\n hideRules: [],\n }),\n },\n enumVariants: [],\n }),\n );\n });\n\n it(\"keys a descriptor without `discriminator_hex` under the empty string\", async () => {\n // Single-instruction programs (e.g. SPL Memo `addMemo`) genuinely have no\n // discriminator, so CAL omits the field.\n httpMock.get.mockResolvedValue([\n {\n id: programId,\n chain_id: SolanaTransactionScanChainId.MAINNET,\n instructions: [\n {\n instruction_name: \"addMemo\",\n descriptor: {\n data: \"00010101\",\n signatures: { prod: \"prodsig\", test: \"testsig\" },\n },\n },\n ],\n },\n ]);\n\n const result = await datasource.getInstructionInfo({ programId, network });\n\n expect(result.isRight()).toBe(true);\n const { descriptors } = result.unsafeCoerce();\n expect(Object.keys(descriptors)).toEqual([\"\"]);\n expect(descriptors[\"\"]!.unsafeCoerce()).toEqual(\n expect.objectContaining({\n programId,\n discriminator: \"\",\n instructionInfo: { data: \"00010101\", signature: \"prodsig\" },\n }),\n );\n });\n\n it(\"returns Left when the response array is empty\", async () => {\n httpMock.get.mockResolvedValue([]);\n\n const result = await datasource.getInstructionInfo({ programId, network });\n\n expect(result).toEqual(\n Left(\n new Error(\n `[ContextModule] HttpInstructionInfoDataSource: empty response for program ${programId}`,\n ),\n ),\n );\n });\n\n it(\"returns Left when no program object matches the requested programId\", async () => {\n httpMock.get.mockResolvedValue([\n {\n id: \"OtherProgram\",\n chain_id: SolanaTransactionScanChainId.MAINNET,\n instructions: [],\n },\n ]);\n\n const result = await datasource.getInstructionInfo({ programId, network });\n\n expect(result).toEqual(\n Left(\n new Error(\n `[ContextModule] HttpInstructionInfoDataSource: no descriptors for program ${programId}`,\n ),\n ),\n );\n });\n\n it(\"returns Left (not a throw) when an instruction descriptor is malformed\", async () => {\n // `descriptor` missing on the instruction \u2014 would crash the loader if the\n // datasource handed it through unvalidated.\n httpMock.get.mockResolvedValue([\n {\n id: programId,\n chain_id: SolanaTransactionScanChainId.MAINNET,\n instructions: [{ discriminator_hex: \"00000000\" }],\n },\n ]);\n\n const result = await datasource.getInstructionInfo({ programId, network });\n\n expect(result.isLeft()).toBe(true);\n expect((result.extract() as Error).message).toMatch(\n new RegExp(\n String.raw`\\[ContextModule\\] HttpInstructionInfoDataSource: malformed descriptors for program ${programId}:`,\n ),\n );\n });\n\n it(\"returns Left when the HTTP client throws\", async () => {\n httpMock.get.mockRejectedValue(new Error(\"network\"));\n\n const result = await datasource.getInstructionInfo({ programId, network });\n\n expect(result).toEqual(\n Left(\n new Error(\n \"[ContextModule] HttpInstructionInfoDataSource: Failed to fetch instruction descriptors: network\",\n ),\n ),\n );\n });\n});\n"],
|
|
5
|
-
"mappings": "AACA,OAAS,QAAAA,EAAM,SAAAC,MAAa,YAC5B,OAAS,c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DmkNetworkClient } from \"@ledgerhq/device-management-kit\";\nimport { Left, Right } from \"purify-ts\";\nimport { beforeEach, describe, expect, it, vi } from \"vitest\";\n\nimport { type ContextModuleServiceConfig } from \"@/config/model/ContextModuleConfig\";\nimport { SolanaTransactionScanChainId } from \"@/modules/solana/model/SolanaTransactionScanChainId\";\n\nimport { HttpInstructionInfoDataSource } from \"./HttpInstructionInfoDataSource\";\nimport { type InstructionInfoDataSource } from \"./InstructionInfoDataSource\";\nimport { type CalInstructionInfoResponseDto } from \"./InstructionInfoDto\";\n\ndescribe(\"HttpInstructionInfoDataSource\", () => {\n let datasource: InstructionInfoDataSource;\n let httpMock: { get: ReturnType<typeof vi.fn> };\n const programId = \"11111111111111111111111111111111\";\n const network = \"solana-mainnet\";\n const config: ContextModuleServiceConfig = {\n cal: {\n url: \"https://global.api.prd.ledger.com/cal/v1\",\n mode: \"prod\",\n branch: \"main\",\n },\n } as ContextModuleServiceConfig;\n\n const successResponse: CalInstructionInfoResponseDto = [\n {\n id: programId,\n chain_id: SolanaTransactionScanChainId.MAINNET,\n instructions: [\n {\n discriminator_hex: \"00000000\",\n instruction_name: \"createAccount\",\n descriptor: {\n data: \"00010101\",\n signatures: { prod: \"prodsig\", test: \"testsig\" },\n },\n display_fields: [],\n value_flow_ports: [],\n hide_rules: [],\n account_resets: [],\n },\n ],\n },\n ];\n\n beforeEach(() => {\n vi.clearAllMocks();\n httpMock = { get: vi.fn() };\n datasource = new HttpInstructionInfoDataSource(\n config,\n httpMock as unknown as DmkNetworkClient,\n );\n });\n\n it(\"calls CAL /solana_programs with id, chain_id and output params\", async () => {\n httpMock.get.mockResolvedValue(successResponse);\n\n await datasource.getInstructionInfo({ programId, network });\n\n expect(httpMock.get).toHaveBeenCalledTimes(1);\n expect(httpMock.get).toHaveBeenCalledWith(\n \"https://global.api.prd.ledger.com/cal/v1/solana_programs\",\n {\n params: {\n id: programId,\n chain_id: SolanaTransactionScanChainId.MAINNET,\n output: \"id,chain_id,instructions\",\n ref: \"branch:main\",\n },\n },\n );\n });\n\n it(\"maps devnet/testnet networks to their numeric chain ids\", async () => {\n httpMock.get.mockResolvedValue(successResponse);\n\n await datasource.getInstructionInfo({\n programId,\n network: \"solana-devnet\",\n });\n\n expect(httpMock.get).toHaveBeenCalledWith(\n \"https://global.api.prd.ledger.com/cal/v1/solana_programs\",\n expect.objectContaining({\n params: expect.objectContaining({ chain_id: 901 }),\n }),\n );\n });\n\n it(\"returns Right with each descriptor transformed into the core payload on success\", async () => {\n httpMock.get.mockResolvedValue(successResponse);\n\n const result = await datasource.getInstructionInfo({ programId, network });\n\n expect(result).toEqual(\n Right({\n programId,\n descriptors: {\n \"00000000\": Right({\n programId,\n discriminator: \"00000000\",\n instructionName: \"createAccount\",\n instructionInfo: { data: \"00010101\", signature: \"prodsig\" },\n substructures: [],\n enumVariants: [],\n idlDescriptor: { typePool: [], rootType: 0 },\n mintAssociations: [],\n ownerAssociations: [],\n valueFlowPorts: [],\n accountResets: [],\n displayFields: [],\n hideRules: [],\n }),\n },\n enumVariants: [],\n }),\n );\n });\n\n it(\"keys a descriptor without `discriminator_hex` under the empty string\", async () => {\n // Single-instruction programs (e.g. SPL Memo `addMemo`) genuinely have no\n // discriminator, so CAL omits the field.\n httpMock.get.mockResolvedValue([\n {\n id: programId,\n chain_id: SolanaTransactionScanChainId.MAINNET,\n instructions: [\n {\n instruction_name: \"addMemo\",\n descriptor: {\n data: \"00010101\",\n signatures: { prod: \"prodsig\", test: \"testsig\" },\n },\n },\n ],\n },\n ]);\n\n const result = await datasource.getInstructionInfo({ programId, network });\n\n expect(result.isRight()).toBe(true);\n const { descriptors } = result.unsafeCoerce();\n expect(Object.keys(descriptors)).toEqual([\"\"]);\n expect(descriptors[\"\"]!.unsafeCoerce()).toEqual(\n expect.objectContaining({\n programId,\n discriminator: \"\",\n instructionInfo: { data: \"00010101\", signature: \"prodsig\" },\n }),\n );\n });\n\n it(\"returns Left when the response array is empty\", async () => {\n httpMock.get.mockResolvedValue([]);\n\n const result = await datasource.getInstructionInfo({ programId, network });\n\n expect(result).toEqual(\n Left(\n new Error(\n `[ContextModule] HttpInstructionInfoDataSource: empty response for program ${programId}`,\n ),\n ),\n );\n });\n\n it(\"returns Left when no program object matches the requested programId\", async () => {\n httpMock.get.mockResolvedValue([\n {\n id: \"OtherProgram\",\n chain_id: SolanaTransactionScanChainId.MAINNET,\n instructions: [],\n },\n ]);\n\n const result = await datasource.getInstructionInfo({ programId, network });\n\n expect(result).toEqual(\n Left(\n new Error(\n `[ContextModule] HttpInstructionInfoDataSource: no descriptors for program ${programId}`,\n ),\n ),\n );\n });\n\n it(\"returns Left (not a throw) when an instruction descriptor is malformed\", async () => {\n // `descriptor` missing on the instruction \u2014 would crash the loader if the\n // datasource handed it through unvalidated.\n httpMock.get.mockResolvedValue([\n {\n id: programId,\n chain_id: SolanaTransactionScanChainId.MAINNET,\n instructions: [{ discriminator_hex: \"00000000\" }],\n },\n ]);\n\n const result = await datasource.getInstructionInfo({ programId, network });\n\n expect(result.isLeft()).toBe(true);\n expect((result.extract() as Error).message).toMatch(\n new RegExp(\n String.raw`\\[ContextModule\\] HttpInstructionInfoDataSource: malformed descriptors for program ${programId}:`,\n ),\n );\n });\n\n it(\"returns Left (not a throw) when account_schema.slots is not an array\", async () => {\n // Regression: account_schema was not codec-validated, so a malformed\n // shape (e.g. `slots` as an object instead of an array) bypassed\n // validation here and crashed later in the mapper's `.map()` call instead\n // of degrading gracefully to a per-program error.\n httpMock.get.mockResolvedValue([\n {\n id: programId,\n chain_id: SolanaTransactionScanChainId.MAINNET,\n instructions: [\n {\n discriminator_hex: \"00000000\",\n descriptor: {\n data: \"00010101\",\n signatures: { prod: \"prodsig\", test: \"testsig\" },\n },\n account_schema: { slots: {} },\n },\n ],\n },\n ]);\n\n const result = await datasource.getInstructionInfo({ programId, network });\n\n expect(result.isLeft()).toBe(true);\n expect((result.extract() as Error).message).toMatch(\n new RegExp(\n String.raw`\\[ContextModule\\] HttpInstructionInfoDataSource: malformed descriptors for program ${programId}:`,\n ),\n );\n });\n\n it(\"returns Right with accountSchema mapped through when it is well-formed\", async () => {\n httpMock.get.mockResolvedValue([\n {\n id: programId,\n chain_id: SolanaTransactionScanChainId.MAINNET,\n instructions: [\n {\n discriminator_hex: \"00000000\",\n descriptor: {\n data: \"00010101\",\n signatures: { prod: \"prodsig\", test: \"testsig\" },\n },\n account_schema: {\n count_min: 2,\n count_max: 2,\n slots: [{ signer: \"REQUIRED\", writable: \"EITHER\" }],\n },\n },\n ],\n },\n ]);\n\n const result = await datasource.getInstructionInfo({ programId, network });\n\n expect(result.isRight()).toBe(true);\n const { descriptors } = result.unsafeCoerce();\n expect(descriptors[\"00000000\"]!.unsafeCoerce()).toEqual(\n expect.objectContaining({\n accountSchema: {\n count_min: 2,\n count_max: 2,\n remaining_policy: { signer: \"EITHER\", writable: \"EITHER\" },\n slots: [{ signer: \"REQUIRED\", writable: \"EITHER\" }],\n },\n }),\n );\n });\n\n it(\"returns Left when the HTTP client throws\", async () => {\n httpMock.get.mockRejectedValue(new Error(\"network\"));\n\n const result = await datasource.getInstructionInfo({ programId, network });\n\n expect(result).toEqual(\n Left(\n new Error(\n \"[ContextModule] HttpInstructionInfoDataSource: Failed to fetch instruction descriptors: network\",\n ),\n ),\n );\n });\n});\n"],
|
|
5
|
+
"mappings": "AACA,OAAS,QAAAA,EAAM,SAAAC,MAAa,YAC5B,OAAS,cAAAC,EAAY,YAAAC,EAAU,UAAAC,EAAQ,MAAAC,EAAI,MAAAC,MAAU,SAGrD,OAAS,gCAAAC,MAAoC,sDAE7C,OAAS,iCAAAC,MAAqC,kCAI9CL,EAAS,gCAAiC,IAAM,CAC9C,IAAIM,EACAC,EACJ,MAAMC,EAAY,mCACZC,EAAU,iBACVC,EAAqC,CACzC,IAAK,CACH,IAAK,2CACL,KAAM,OACN,OAAQ,MACV,CACF,EAEMC,EAAiD,CACrD,CACE,GAAIH,EACJ,SAAUJ,EAA6B,QACvC,aAAc,CACZ,CACE,k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nB,WAAY,CACV,KAAM,WACN,WAAY,CAAE,KAAM,UAAW,KAAM,SAAU,CACjD,EACA,eAAgB,CACd,UAAW,EACX,UAAW,EACX,MAAO,CAAC,CAAE,OAAQ,WAAY,SAAU,QAAS,CAAC,CACpD,CACF,CACF,CACF,CACF,CAAC,EAED,MAAMQ,EAAS,MAAMN,EAAW,mBAAmB,CAAE,UAAAE,EAAW,QAAAC,CAAQ,CAAC,EAEzER,EAAOW,EAAO,QAAQ,CAAC,EAAE,KAAK,EAAI,EAClC,KAAM,CAAE,YAAAC,CAAY,EAAID,EAAO,aAAa,EAC5CX,EAAOY,EAAY,UAAU,EAAG,aAAa,CAAC,EAAE,QAC9CZ,EAAO,iBAAiB,CACtB,cAAe,CACb,UAAW,EACX,UAAW,EACX,iBAAkB,CAAE,OAAQ,SAAU,SAAU,QAAS,EACzD,MAAO,CAAC,CAAE,OAAQ,WAAY,SAAU,QAAS,CAAC,CACpD,CACF,CAAC,CACH,CACF,CAAC,EAEDC,EAAG,2CAA4C,SAAY,CACzDK,EAAS,IAAI,kBAAkB,IAAI,MAAM,SAAS,CAAC,EAEnD,MAAMK,EAAS,MAAMN,EAAW,mBAAmB,CAAE,UAAAE,EAAW,QAAAC,CAAQ,CAAC,EAEzER,EAAOW,CAAM,EAAE,QACbf,EACE,IAAI,MACF,iGACF,CACF,CACF,CACF,CAAC,CACH,CAAC",
|
|
6
6
|
"names": ["Left", "Right", "beforeEach", "describe", "expect", "it", "vi", "SolanaTransactionScanChainId", "HttpInstructionInfoDataSource", "datasource", "httpMock", "programId", "network", "config", "successResponse", "result", "descriptors"]
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{array as
|
|
1
|
+
import{array as o,Codec as n,number as a,optional as t,record as i,string as e}from"purify-ts";const l=n.interface({prod:t(e),test:t(e)}),c=n.interface({data:e,signatures:l}),u=n.interface({descriptor:c}),r=n.interface({descriptor:e}),s=n.interface({signer:e,writable:e}),p=n.interface({count_min:t(a),count_max:t(a),remaining_policy:t(s),slots:t(o(s))}),d=n.interface({discriminator_hex:t(e),descriptor:c,enum_variants:t(i(e,i(e,u))),display_fields:t(o(r)),value_flow_ports:t(o(r)),hide_rules:t(o(r)),account_resets:t(o(r)),account_schema:t(p)}),_=n.interface({id:e,chain_id:a,instructions:o(d)});export{_ as calInstructionProgramCodec};
|
|
2
2
|
//# sourceMappingURL=InstructionInfoDto.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../../src/modules/solana/instruction-info/data/InstructionInfoDto.ts"],
|
|
4
|
-
"sourcesContent": ["// DTO + codecs for the CAL instruction-descriptors response (one object per\n// `programId`, wrapped in a JSON array).\n//\n// The hand-written types describe the consumed shape (with genuinely optional\n// `?:` fields); the codecs below validate that shape at runtime so\n// `HttpInstructionInfoDataSource` can hand the loaders a payload they can\n// dereference without runtime-throwing on a malformed descriptor.\n\nimport { array, Codec, number, optional, record, string } from \"purify-ts\";\n\nexport type CalSignatures = {\n prod?: string;\n test?: string;\n};\n\nexport type CalSignedDescriptorDto = {\n data: string;\n signatures: CalSignatures;\n};\n\n// Decoded CAL JSON shapes (snake_case mirrors the CAL response) that drive\n// host-side requirement building.\n\nexport type CalValueDto = {\n source: string;\n account_index?: number;\n data?: string;\n path?: { steps: number[] };\n};\n\nexport type CalTokenValueDto = {\n kind: string;\n value?: CalValueDto;\n account_index?: number;\n /** `RESOLVE` only: account index whose address is the mint of last resort. */\n fallback_account?: number;\n};\n\nexport type CalMintAssociationDto = {\n account_index: number;\n mint_index: number;\n};\n\n// Neither half is codec-validated, and the spec requires both or neither, so\n// both are optional here and the mapper drops a half-declared pair.\nexport type CalOwnerAssociationDto = {\n account_index?: number;\n owner?: CalValueDto;\n};\n\n/** One `ACTIVE_WHEN` predicate: a bare name, or `MINT_PREDICATE` + its mint. */\nexport type CalActiveWhenPredicateDto =\n | string\n | { kind: string; mint?: string };\n\nexport type CalTypePoolEntryDto = {\n index: number;\n kind: string;\n refs?: number[];\n size?: number;\n encoding?: number;\n len_kind?: string;\n flag_kind?: string;\n sentinel?: string;\n disc_kind?: string;\n total_variants?: number;\n enum_id?: string;\n};\n\nexport type CalEnumVariantDto = {\n variant_name: string;\n payload_kind?: string;\n descriptor: CalSignedDescriptorDto;\n};\n\n/** A substructure CAL serves only as opaque TLV (e.g. HIDE_RULE). */\nexport type CalSubstructureDto = {\n descriptor: string;\n};\n\nexport type CalValueFlowPortDto = CalSubstructureDto & {\n account_indices: number[];\n optional_account_strategy?: string;\n token_value: CalTokenValueDto;\n active_when?: CalActiveWhenPredicateDto[];\n};\n\nexport type CalHideRuleDto = CalSubstructureDto & {\n rule_set_index?: number;\n target?: CalValueDto;\n condition?: string;\n};\n\nexport type CalAccountResetDto = CalSubstructureDto & {\n account_index?: number;\n require_pre_balance_zero?: boolean;\n};\n\nexport type CalDisplayFieldDto = CalSubstructureDto & {\n name?: string;\n param?: { type: string; value?: CalValueDto; token?: CalValueDto };\n};\n\nexport type CalInstructionDescriptorDto = {\n discriminator_hex?: string;\n instruction_name?: string;\n descriptor: CalSignedDescriptorDto;\n idl_descriptor?: {\n type_pool?: CalTypePoolEntryDto[];\n root_type?: number;\n };\n mint_association?: CalMintAssociationDto;\n owner_association?: CalOwnerAssociationDto;\n enum_variants?: Record<string, Record<string, CalEnumVariantDto>>;\n display_fields?: CalDisplayFieldDto[];\n value_flow_ports?: CalValueFlowPortDto[];\n hide_rules?: CalHideRuleDto[];\n account_resets?: CalAccountResetDto[];\n};\n\n// One program object of the `solana_programs` response: the program `id`, its\n// `chain_id`, and the flat `instructions` array (keyed downstream by\n// `discriminator_hex`).\nexport type CalInstructionProgramDto = {\n id: string;\n chain_id: number;\n instructions: CalInstructionDescriptorDto[];\n};\n\n// Outer shape: array of program objects (one per requested `id`).\nexport type CalInstructionInfoResponseDto = CalInstructionProgramDto[];\n\n// --- Validation codecs (runtime). Validate only the fields the loaders read;\n// `Codec.interface` ignores unknown extras so CAL can add fields freely. ---\n\nconst calSignaturesCodec = Codec.interface({\n prod: optional(string),\n test: optional(string),\n});\n\nconst calSignedDescriptorCodec = Codec.interface({\n data: string,\n signatures: calSignaturesCodec,\n});\n\nconst calEnumVariantCodec = Codec.interface({\n descriptor: calSignedDescriptorCodec,\n});\n\nconst calSubstructureCodec = Codec.interface({\n descriptor: string,\n});\n\nconst calInstructionDescriptorCodec = Codec.interface({\n discriminator_hex: optional(string),\n descriptor: calSignedDescriptorCodec,\n enum_variants: optional(record(string, record(string, calEnumVariantCodec))),\n display_fields: optional(array(calSubstructureCodec)),\n value_flow_ports: optional(array(calSubstructureCodec)),\n hide_rules: optional(array(calSubstructureCodec)),\n account_resets: optional(array(calSubstructureCodec)),\n});\n\n/**\n * Codec for one program object of the `solana_programs` response. Used by the\n * datasource to validate the CAL payload before handing it to the loaders.\n * Only loader-consumed fields are validated; unrelated CAL fields\n * (`idl_descriptor`, `mint_association`, \u2026) are ignored.\n */\nexport const calInstructionProgramCodec = Codec.interface({\n id: string,\n chain_id: number,\n instructions: array(calInstructionDescriptorCodec),\n});\n"],
|
|
5
|
-
"mappings": "AAQA,OAAS,SAAAA,EAAO,SAAAC,EAAO,UAAAC,EAAQ,YAAAC,EAAU,UAAAC,EAAQ,UAAAC,MAAc,
|
|
6
|
-
"names": ["array", "Codec", "number", "optional", "record", "string", "calSignaturesCodec", "calSignedDescriptorCodec", "calEnumVariantCodec", "calSubstructureCodec", "calInstructionDescriptorCodec", "calInstructionProgramCodec"]
|
|
4
|
+
"sourcesContent": ["// DTO + codecs for the CAL instruction-descriptors response (one object per\n// `programId`, wrapped in a JSON array).\n//\n// The hand-written types describe the consumed shape (with genuinely optional\n// `?:` fields); the codecs below validate that shape at runtime so\n// `HttpInstructionInfoDataSource` can hand the loaders a payload they can\n// dereference without runtime-throwing on a malformed descriptor.\n\nimport { array, Codec, number, optional, record, string } from \"purify-ts\";\n\nexport type CalSignatures = {\n prod?: string;\n test?: string;\n};\n\nexport type CalSignedDescriptorDto = {\n data: string;\n signatures: CalSignatures;\n};\n\n// Decoded CAL JSON shapes (snake_case mirrors the CAL response) that drive\n// host-side requirement building.\n\nexport type CalValueDto = {\n source: string;\n account_index?: number;\n data?: string;\n path?: { steps: number[] };\n};\n\nexport type CalTokenValueDto = {\n kind: string;\n value?: CalValueDto;\n account_index?: number;\n /** `RESOLVE` only: account index whose address is the mint of last resort. */\n fallback_account?: number;\n};\n\nexport type CalMintAssociationDto = {\n account_index: number;\n mint_index: number;\n};\n\n// Neither half is codec-validated, and the spec requires both or neither, so\n// both are optional here and the mapper drops a half-declared pair.\nexport type CalOwnerAssociationDto = {\n account_index?: number;\n owner?: CalValueDto;\n};\n\n/** One `ACTIVE_WHEN` predicate: a bare name, or `MINT_PREDICATE` + its mint. */\nexport type CalActiveWhenPredicateDto =\n | string\n | { kind: string; mint?: string };\n\nexport type CalTypePoolEntryDto = {\n index: number;\n kind: string;\n refs?: number[];\n size?: number;\n encoding?: number;\n len_kind?: string;\n flag_kind?: string;\n sentinel?: string;\n disc_kind?: string;\n total_variants?: number;\n enum_id?: string;\n};\n\nexport type CalEnumVariantDto = {\n variant_name: string;\n payload_kind?: string;\n descriptor: CalSignedDescriptorDto;\n};\n\n/** A substructure CAL serves only as opaque TLV (e.g. HIDE_RULE). */\nexport type CalSubstructureDto = {\n descriptor: string;\n};\n\nexport type CalValueFlowPortDto = CalSubstructureDto & {\n account_indices: number[];\n optional_account_strategy?: string;\n token_value: CalTokenValueDto;\n active_when?: CalActiveWhenPredicateDto[];\n};\n\nexport type CalHideRuleDto = CalSubstructureDto & {\n rule_set_index?: number;\n target?: CalValueDto;\n condition?: string;\n};\n\nexport type CalAccountResetDto = CalSubstructureDto & {\n account_index?: number;\n require_pre_balance_zero?: boolean;\n value_kind?: string;\n token?: CalTokenValueDto;\n require_native_pre_balance_zero?: boolean;\n};\n\nexport type CalSlotConstraintDto = {\n signer: string;\n writable: string;\n};\n\nexport type CalAccountSchemaDto = {\n count_min?: number;\n count_max?: number;\n remaining_policy?: CalSlotConstraintDto;\n slots?: CalSlotConstraintDto[];\n};\n\nexport type CalDisplayFieldDto = CalSubstructureDto & {\n name?: string;\n param?: { type: string; value?: CalValueDto; token?: CalValueDto };\n};\n\nexport type CalInstructionDescriptorDto = {\n discriminator_hex?: string;\n instruction_name?: string;\n descriptor: CalSignedDescriptorDto;\n idl_descriptor?: {\n type_pool?: CalTypePoolEntryDto[];\n root_type?: number;\n };\n mint_association?: CalMintAssociationDto;\n owner_association?: CalOwnerAssociationDto;\n enum_variants?: Record<string, Record<string, CalEnumVariantDto>>;\n display_fields?: CalDisplayFieldDto[];\n value_flow_ports?: CalValueFlowPortDto[];\n hide_rules?: CalHideRuleDto[];\n account_resets?: CalAccountResetDto[];\n /** Absent means \"no ACCOUNT_SCHEMA check\". */\n account_schema?: CalAccountSchemaDto;\n};\n\n// One program object of the `solana_programs` response: the program `id`, its\n// `chain_id`, and the flat `instructions` array (keyed downstream by\n// `discriminator_hex`).\nexport type CalInstructionProgramDto = {\n id: string;\n chain_id: number;\n instructions: CalInstructionDescriptorDto[];\n};\n\n// Outer shape: array of program objects (one per requested `id`).\nexport type CalInstructionInfoResponseDto = CalInstructionProgramDto[];\n\n// --- Validation codecs (runtime). Validate only the fields the loaders read;\n// `Codec.interface` ignores unknown extras so CAL can add fields freely. ---\n\nconst calSignaturesCodec = Codec.interface({\n prod: optional(string),\n test: optional(string),\n});\n\nconst calSignedDescriptorCodec = Codec.interface({\n data: string,\n signatures: calSignaturesCodec,\n});\n\nconst calEnumVariantCodec = Codec.interface({\n descriptor: calSignedDescriptorCodec,\n});\n\nconst calSubstructureCodec = Codec.interface({\n descriptor: string,\n});\n\nconst calSlotConstraintCodec = Codec.interface({\n signer: string,\n writable: string,\n});\n\nconst calAccountSchemaCodec = Codec.interface({\n count_min: optional(number),\n count_max: optional(number),\n remaining_policy: optional(calSlotConstraintCodec),\n slots: optional(array(calSlotConstraintCodec)),\n});\n\nconst calInstructionDescriptorCodec = Codec.interface({\n discriminator_hex: optional(string),\n descriptor: calSignedDescriptorCodec,\n enum_variants: optional(record(string, record(string, calEnumVariantCodec))),\n display_fields: optional(array(calSubstructureCodec)),\n value_flow_ports: optional(array(calSubstructureCodec)),\n hide_rules: optional(array(calSubstructureCodec)),\n account_resets: optional(array(calSubstructureCodec)),\n account_schema: optional(calAccountSchemaCodec),\n});\n\n/**\n * Codec for one program object of the `solana_programs` response. Used by the\n * datasource to validate the CAL payload before handing it to the loaders.\n * Only loader-consumed fields are validated; unrelated CAL fields\n * (`idl_descriptor`, `mint_association`, \u2026) are ignored.\n */\nexport const calInstructionProgramCodec = Codec.interface({\n id: string,\n chain_id: number,\n instructions: array(calInstructionDescriptorCodec),\n});\n"],
|
|
5
|
+
"mappings": "AAQA,OAAS,SAAAA,EAAO,SAAAC,EAAO,UAAAC,EAAQ,YAAAC,EAAU,UAAAC,EAAQ,UAAAC,MAAc,YAgJ/D,MAAMC,EAAqBL,EAAM,UAAU,CACzC,KAAME,EAASE,CAAM,EACrB,KAAMF,EAASE,CAAM,CACvB,CAAC,EAEKE,EAA2BN,EAAM,UAAU,CAC/C,KAAMI,EACN,WAAYC,CACd,CAAC,EAEKE,EAAsBP,EAAM,UAAU,CAC1C,WAAYM,CACd,CAAC,EAEKE,EAAuBR,EAAM,UAAU,CAC3C,WAAYI,CACd,CAAC,EAEKK,EAAyBT,EAAM,UAAU,CAC7C,OAAQI,EACR,SAAUA,CACZ,CAAC,EAEKM,EAAwBV,EAAM,UAAU,CAC5C,UAAWE,EAASD,CAAM,EAC1B,UAAWC,EAASD,CAAM,EAC1B,iBAAkBC,EAASO,CAAsB,EACjD,MAAOP,EAASH,EAAMU,CAAsB,CAAC,CAC/C,CAAC,EAEKE,EAAgCX,EAAM,UAAU,CACpD,kBAAmBE,EAASE,CAAM,EAClC,WAAYE,EACZ,cAAeJ,EAASC,EAAOC,EAAQD,EAAOC,EAAQG,CAAmB,CAAC,CAAC,EAC3E,eAAgBL,EAASH,EAAMS,CAAoB,CAAC,EACpD,iBAAkBN,EAASH,EAAMS,CAAoB,CAAC,EACtD,WAAYN,EAASH,EAAMS,CAAoB,CAAC,EAChD,eAAgBN,EAASH,EAAMS,CAAoB,CAAC,EACpD,eAAgBN,EAASQ,CAAqB,CAChD,CAAC,EAQYE,EAA6BZ,EAAM,UAAU,CACxD,GAAII,EACJ,SAAUH,EACV,aAAcF,EAAMY,CAA6B,CACnD,CAAC",
|
|
6
|
+
"names": ["array", "Codec", "number", "optional", "record", "string", "calSignaturesCodec", "calSignedDescriptorCodec", "calEnumVariantCodec", "calSubstructureCodec", "calSlotConstraintCodec", "calAccountSchemaCodec", "calInstructionDescriptorCodec", "calInstructionProgramCodec"]
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Left as
|
|
1
|
+
import{Left as d,Right as C}from"purify-ts";import{SolanaInstructionSubstructureKind as i}from"../../../../modules/solana/model/SolanaPayloads";import{u16Codec as S}from"../../../../shared/utils/uIntCodec";function l(n,t){return n[t]}function f(n=[]){return n.map(t=>({account_indices:t.account_indices,optional_account_strategy:t.optional_account_strategy,token_value:t.token_value,active_when:t.active_when}))}function m(n=[]){return n.flatMap(t=>t.account_index===void 0?[]:[{account_index:t.account_index,require_pre_balance_zero:t.require_pre_balance_zero,value_kind:t.value_kind,token:t.token,require_native_pre_balance_zero:t.require_native_pre_balance_zero}])}function y(n=[]){return n.map(t=>({rule_set_index:t.rule_set_index,target:t.target,condition:t.condition}))}function D(n){return n===void 0?[]:n.account_index===void 0||n.owner===void 0?[]:[{account_index:n.account_index,owner:n.owner}]}const c=new Set(["FORBIDDEN","EITHER","REQUIRED"]);function u(n){const t=c.has(n.signer)?n.signer:"EITHER",a=c.has(n.writable)?n.writable:"EITHER";return{signer:t,writable:a}}function I(n){if(n!==void 0)return{count_min:n.count_min??0,count_max:n.count_max??255,remaining_policy:n.remaining_policy?u(n.remaining_policy):{signer:"EITHER",writable:"EITHER"},slots:(n.slots??[]).map(u)}}function E(n=[]){return n.map(t=>({name:t.name,param:t.param??{type:""}}))}function w(n){return[...(n.display_fields??[]).map(t=>({kind:i.DISPLAY_FIELD,data:t.descriptor})),...(n.value_flow_ports??[]).map(t=>({kind:i.VALUE_FLOW_PORT,data:t.descriptor})),...(n.hide_rules??[]).map(t=>({kind:i.HIDE_RULE,data:t.descriptor})),...(n.account_resets??[]).map(t=>({kind:i.ACCOUNT_RESET,data:t.descriptor}))]}function p(n,t){const a=[];for(const[e,o]of Object.entries(n.enum_variants??{}))for(const[_,r]of Object.entries(o)){const s=Number(_);S.decode(s).isLeft()||a.push({enumId:e,variantIndex:s,descriptor:{data:r.descriptor.data,signature:l(r.descriptor.signatures,t)??""}})}return a}function A(n,t){return Object.values(n).flatMap(a=>p(a,t))}function b(n,t,a,e){const o=l(a.descriptor.signatures,e);return o?C({programId:n,discriminator:t,instructionName:a.instruction_name,instructionInfo:{data:a.descriptor.data,signature:o},substructures:w(a),enumVariants:p(a,e),idlDescriptor:{typePool:a.idl_descriptor?.type_pool??[],rootType:a.idl_descriptor?.root_type??0},mintAssociations:a.mint_association?[a.mint_association]:[],ownerAssociations:D(a.owner_association),valueFlowPorts:f(a.value_flow_ports),accountResets:m(a.account_resets),displayFields:E(a.display_fields),hideRules:y(a.hide_rules),accountSchema:I(a.account_schema)}):d(new Error(`[ContextModule] InstructionInfoDataSource: missing '${e}' signature for (${n}, ${t})`))}export{m as toAccountResets,I as toAccountSchema,E as toDisplayFields,y as toHideRules,b as toInstructionInfoPayload,D as toOwnerAssociations,A as toProgramEnumVariants,f as toValueFlowPorts};
|
|
2
2
|
//# sourceMappingURL=InstructionInfoMapper.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../../src/modules/solana/instruction-info/data/InstructionInfoMapper.ts"],
|
|
4
|
-
"sourcesContent": ["// Maps the validated CAL instruction-descriptor DTOs into the core\n// `SolanaInstructionInfoPayload` model. Keeping this in the data layer means\n// the domain `InstructionInfoContextLoader` never has to know the CAL DTO\n// shapes \u2014 it consumes core models only.\n\nimport { type Either, Left, Right } from \"purify-ts\";\n\nimport {\n type SolanaCalAccountReset,\n type SolanaCalDisplayField,\n type SolanaCalHideRule,\n type SolanaCalOwnerAssociation,\n type SolanaCalValueFlowPort,\n type SolanaInstructionEnumVariant,\n type SolanaInstructionInfoPayload,\n type SolanaInstructionSubstructure,\n SolanaInstructionSubstructureKind,\n} from \"@/modules/solana/model/SolanaPayloads\";\nimport { u16Codec } from \"@/shared/utils/uIntCodec\";\n\nimport {\n type CalAccountResetDto,\n type CalDisplayFieldDto,\n type CalHideRuleDto,\n type CalInstructionDescriptorDto,\n type CalOwnerAssociationDto,\n type CalSignatures,\n type CalValueFlowPortDto,\n} from \"./InstructionInfoDto\";\n\nexport type CalMode = \"prod\" | \"test\";\n\nfunction pickSignature(\n signatures: CalSignatures,\n mode: CalMode,\n): string | undefined {\n return signatures[mode];\n}\n\n// --- DTO \u2192 decoded-payload projections. Pick only the fields the host-side\n// requirement builder reads, dropping the signed-TLV `descriptor` carried by\n// the DTO. ---\n\nexport function toValueFlowPorts(\n dtos: CalValueFlowPortDto[] = [],\n): SolanaCalValueFlowPort[] {\n return dtos.map((port) => ({\n account_indices: port.account_indices,\n optional_account_strategy: port.optional_account_strategy,\n token_value: port.token_value,\n active_when: port.active_when,\n }));\n}\n\nexport function toAccountResets(\n dtos: CalAccountResetDto[] = [],\n): SolanaCalAccountReset[] {\n // Drop malformed resets (missing account_index) rather than defaulting to\n // slot 0, which would create an unintended TOKEN_ACCOUNT_STATE requirement.\n return dtos.flatMap((reset) =>\n reset.account_index === undefined\n ? []\n : [\n {\n account_index: reset.account_index,\n require_pre_balance_zero: reset.require_pre_balance_zero,\n },\n ],\n );\n}\n\n/**\n * Every rule is carried, including one CAL served without a `condition`. The\n * rule's signed TLV goes to the device through {@link toSubstructures}\n * regardless, and the device resolves the `target` of every rule it receives \u2014\n * so dropping the entry here would cost the host the `ALT_RESOLUTION` for that\n * target and make the device refuse to sign. A missing condition only means no\n * requirement keys off this rule's predicate.\n */\nexport function toHideRules(dtos: CalHideRuleDto[] = []): SolanaCalHideRule[] {\n return dtos.map((rule) => ({\n rule_set_index: rule.rule_set_index,\n target: rule.target,\n condition: rule.condition,\n }));\n}\n\n/**\n * CAL carries at most one `owner_association` per descriptor; the payload holds\n * a list so the transaction-wide owner map is built the same way as the mint\n * map. Both halves of the pair are required (spec: \"must both be present or\n * both absent\"), so a half-declared association is dropped.\n */\nexport function toOwnerAssociations(\n dto: CalOwnerAssociationDto | undefined,\n): SolanaCalOwnerAssociation[] {\n if (dto === undefined) return [];\n if (dto.account_index === undefined || dto.owner === undefined) return [];\n return [{ account_index: dto.account_index, owner: dto.owner }];\n}\n\nexport function toDisplayFields(\n dtos: CalDisplayFieldDto[] = [],\n): SolanaCalDisplayField[] {\n return dtos.map((field) => ({\n name: field.name,\n param: field.param ?? { type: \"\" },\n }));\n}\n\nfunction toSubstructures(\n dto: CalInstructionDescriptorDto,\n): SolanaInstructionSubstructure[] {\n return [\n ...(dto.display_fields ?? []).map((s) => ({\n kind: SolanaInstructionSubstructureKind.DISPLAY_FIELD,\n data: s.descriptor,\n })),\n ...(dto.value_flow_ports ?? []).map((s) => ({\n kind: SolanaInstructionSubstructureKind.VALUE_FLOW_PORT,\n data: s.descriptor,\n })),\n ...(dto.hide_rules ?? []).map((s) => ({\n kind: SolanaInstructionSubstructureKind.HIDE_RULE,\n data: s.descriptor,\n })),\n ...(dto.account_resets ?? []).map((s) => ({\n kind: SolanaInstructionSubstructureKind.ACCOUNT_RESET,\n data: s.descriptor,\n })),\n ];\n}\n\n/**\n * Flatten the CAL-bundled enum variants (keyed enumId \u2192 variantIndex). Keys\n * that don't validate as a u16 are skipped rather than leaking NaN/out-of-range\n * indices into the payload.\n */\nfunction toEnumVariants(\n dto: CalInstructionDescriptorDto,\n mode: CalMode,\n): SolanaInstructionEnumVariant[] {\n const enumVariants: SolanaInstructionEnumVariant[] = [];\n for (const [enumId, variants] of Object.entries(dto.enum_variants ?? {})) {\n for (const [variantIndex, variant] of Object.entries(variants)) {\n const index = Number(variantIndex);\n if (u16Codec.decode(index).isLeft()) {\n continue;\n }\n enumVariants.push({\n enumId,\n variantIndex: index,\n descriptor: {\n data: variant.descriptor.data,\n signature: pickSignature(variant.descriptor.signatures, mode) ?? \"\",\n },\n });\n }\n }\n return enumVariants;\n}\n\n/**\n * Flatten the enum variants of every descriptor in a program into a single\n * list. CAL nests `enum_variants` inside each instruction descriptor but\n * guarantees `(enumId, variantIndex)` is unique across a program, so the enum\n * loader resolves a selection against this program-level list \u2014 independently\n * of whether any individual instruction descriptor carried a usable signature.\n */\nexport function toProgramEnumVariants(\n descriptors: Record<string, CalInstructionDescriptorDto>,\n mode: CalMode,\n): SolanaInstructionEnumVariant[] {\n return Object.values(descriptors).flatMap((dto) => toEnumVariants(dto, mode));\n}\n\n/**\n * Transform one validated CAL descriptor DTO into the core\n * {@link SolanaInstructionInfoPayload}. Returns a `Left` when the descriptor is\n * unusable (no signature for the configured `mode`), so the caller can surface\n * a per-descriptor ERROR rather than emitting an empty signature.\n *\n * `programId` comes from the enclosing `solana_programs` envelope `id`;\n * `discriminator` from the instruction's `discriminator_hex`.\n */\nexport function toInstructionInfoPayload(\n programId: string,\n discriminator: string,\n dto: CalInstructionDescriptorDto,\n mode: CalMode,\n): Either<Error, SolanaInstructionInfoPayload> {\n const signature = pickSignature(dto.descriptor.signatures, mode);\n if (!signature) {\n return Left(\n new Error(\n `[ContextModule] InstructionInfoDataSource: missing '${mode}' signature for (${programId}, ${discriminator})`,\n ),\n );\n }\n\n return Right({\n programId,\n discriminator,\n instructionName: dto.instruction_name,\n instructionInfo: {\n data: dto.descriptor.data,\n signature,\n },\n substructures: toSubstructures(dto),\n enumVariants: toEnumVariants(dto, mode),\n idlDescriptor: {\n typePool: dto.idl_descriptor?.type_pool ?? [],\n rootType: dto.idl_descriptor?.root_type ?? 0,\n },\n mintAssociations: dto.mint_association ? [dto.mint_association] : [],\n ownerAssociations: toOwnerAssociations(dto.owner_association),\n valueFlowPorts: toValueFlowPorts(dto.value_flow_ports),\n accountResets: toAccountResets(dto.account_resets),\n displayFields: toDisplayFields(dto.display_fields),\n hideRules: toHideRules(dto.hide_rules),\n });\n}\n"],
|
|
5
|
-
"mappings": "AAKA,OAAsB,QAAAA,EAAM,SAAAC,MAAa,YAEzC,
|
|
6
|
-
"names": ["Left", "Right", "SolanaInstructionSubstructureKind", "u16Codec", "pickSignature", "signatures", "mode", "toValueFlowPorts", "dtos", "port", "toAccountResets", "reset", "toHideRules", "rule", "toOwnerAssociations", "dto", "toDisplayFields", "field", "toSubstructures", "s", "toEnumVariants", "enumVariants", "enumId", "variants", "variantIndex", "variant", "index", "toProgramEnumVariants", "descriptors", "toInstructionInfoPayload", "programId", "discriminator", "signature"]
|
|
4
|
+
"sourcesContent": ["// Maps the validated CAL instruction-descriptor DTOs into the core\n// `SolanaInstructionInfoPayload` model. Keeping this in the data layer means\n// the domain `InstructionInfoContextLoader` never has to know the CAL DTO\n// shapes \u2014 it consumes core models only.\n\nimport { type Either, Left, Right } from \"purify-ts\";\n\nimport {\n type SolanaCalAccountReset,\n type SolanaCalAccountSchema,\n type SolanaCalDisplayField,\n type SolanaCalHideRule,\n type SolanaCalOwnerAssociation,\n type SolanaCalSlotConstraint,\n type SolanaCalValueFlowPort,\n type SolanaInstructionEnumVariant,\n type SolanaInstructionInfoPayload,\n type SolanaInstructionSubstructure,\n SolanaInstructionSubstructureKind,\n} from \"@/modules/solana/model/SolanaPayloads\";\nimport { u16Codec } from \"@/shared/utils/uIntCodec\";\n\nimport {\n type CalAccountResetDto,\n type CalAccountSchemaDto,\n type CalDisplayFieldDto,\n type CalHideRuleDto,\n type CalInstructionDescriptorDto,\n type CalOwnerAssociationDto,\n type CalSignatures,\n type CalSlotConstraintDto,\n type CalValueFlowPortDto,\n} from \"./InstructionInfoDto\";\n\nexport type CalMode = \"prod\" | \"test\";\n\nfunction pickSignature(\n signatures: CalSignatures,\n mode: CalMode,\n): string | undefined {\n return signatures[mode];\n}\n\n// --- DTO \u2192 decoded-payload projections. Pick only the fields the host-side\n// requirement builder reads, dropping the signed-TLV `descriptor` carried by\n// the DTO. ---\n\nexport function toValueFlowPorts(\n dtos: CalValueFlowPortDto[] = [],\n): SolanaCalValueFlowPort[] {\n return dtos.map((port) => ({\n account_indices: port.account_indices,\n optional_account_strategy: port.optional_account_strategy,\n token_value: port.token_value,\n active_when: port.active_when,\n }));\n}\n\nexport function toAccountResets(\n dtos: CalAccountResetDto[] = [],\n): SolanaCalAccountReset[] {\n // Drop malformed resets (missing account_index) rather than defaulting to\n // slot 0, which would create an unintended TOKEN_ACCOUNT_STATE requirement.\n return dtos.flatMap((reset) =>\n reset.account_index === undefined\n ? []\n : [\n {\n account_index: reset.account_index,\n require_pre_balance_zero: reset.require_pre_balance_zero,\n value_kind: reset.value_kind,\n token: reset.token,\n require_native_pre_balance_zero:\n reset.require_native_pre_balance_zero,\n },\n ],\n );\n}\n\n/**\n * Every rule is carried, including one CAL served without a `condition`. The\n * rule's signed TLV goes to the device through {@link toSubstructures}\n * regardless, and the device resolves the `target` of every rule it receives \u2014\n * so dropping the entry here would cost the host the `ALT_RESOLUTION` for that\n * target and make the device refuse to sign. A missing condition only means no\n * requirement keys off this rule's predicate.\n */\nexport function toHideRules(dtos: CalHideRuleDto[] = []): SolanaCalHideRule[] {\n return dtos.map((rule) => ({\n rule_set_index: rule.rule_set_index,\n target: rule.target,\n condition: rule.condition,\n }));\n}\n\n/**\n * CAL carries at most one `owner_association` per descriptor; the payload holds\n * a list so the transaction-wide owner map is built the same way as the mint\n * map. Both halves of the pair are required (spec: \"must both be present or\n * both absent\"), so a half-declared association is dropped.\n */\nexport function toOwnerAssociations(\n dto: CalOwnerAssociationDto | undefined,\n): SolanaCalOwnerAssociation[] {\n if (dto === undefined) return [];\n if (dto.account_index === undefined || dto.owner === undefined) return [];\n return [{ account_index: dto.account_index, owner: dto.owner }];\n}\n\nconst VALID_CONSTRAINT_VALUES = new Set([\"FORBIDDEN\", \"EITHER\", \"REQUIRED\"]);\n\n/**\n * Unlike `value_kind` on `ACCOUNT_RESET` (an unknown value is a decode\n * error), an unknown/missing `signer` or `writable` here deliberately fails\n * open to `\"EITHER\"` \u2014 i.e. that slot is left unchecked rather than the whole\n * descriptor rejected. ACCOUNT_SCHEMA is only a host-side optimization (the\n * device is the authority at FINALIZE), so the worst outcome of a malformed\n * value is a missed early exit, not an incorrect signature.\n */\nfunction toSlotConstraint(dto: CalSlotConstraintDto): SolanaCalSlotConstraint {\n const signer = VALID_CONSTRAINT_VALUES.has(dto.signer)\n ? (dto.signer as SolanaCalSlotConstraint[\"signer\"])\n : \"EITHER\";\n const writable = VALID_CONSTRAINT_VALUES.has(dto.writable)\n ? (dto.writable as SolanaCalSlotConstraint[\"writable\"])\n : \"EITHER\";\n return { signer, writable };\n}\n\nexport function toAccountSchema(\n dto: CalAccountSchemaDto | undefined,\n): SolanaCalAccountSchema | undefined {\n if (dto === undefined) return undefined;\n return {\n count_min: dto.count_min ?? 0,\n count_max: dto.count_max ?? 255,\n remaining_policy: dto.remaining_policy\n ? toSlotConstraint(dto.remaining_policy)\n : { signer: \"EITHER\", writable: \"EITHER\" },\n slots: (dto.slots ?? []).map(toSlotConstraint),\n };\n}\n\nexport function toDisplayFields(\n dtos: CalDisplayFieldDto[] = [],\n): SolanaCalDisplayField[] {\n return dtos.map((field) => ({\n name: field.name,\n param: field.param ?? { type: \"\" },\n }));\n}\n\nfunction toSubstructures(\n dto: CalInstructionDescriptorDto,\n): SolanaInstructionSubstructure[] {\n return [\n ...(dto.display_fields ?? []).map((s) => ({\n kind: SolanaInstructionSubstructureKind.DISPLAY_FIELD,\n data: s.descriptor,\n })),\n ...(dto.value_flow_ports ?? []).map((s) => ({\n kind: SolanaInstructionSubstructureKind.VALUE_FLOW_PORT,\n data: s.descriptor,\n })),\n ...(dto.hide_rules ?? []).map((s) => ({\n kind: SolanaInstructionSubstructureKind.HIDE_RULE,\n data: s.descriptor,\n })),\n ...(dto.account_resets ?? []).map((s) => ({\n kind: SolanaInstructionSubstructureKind.ACCOUNT_RESET,\n data: s.descriptor,\n })),\n ];\n}\n\n/**\n * Flatten the CAL-bundled enum variants (keyed enumId \u2192 variantIndex). Keys\n * that don't validate as a u16 are skipped rather than leaking NaN/out-of-range\n * indices into the payload.\n */\nfunction toEnumVariants(\n dto: CalInstructionDescriptorDto,\n mode: CalMode,\n): SolanaInstructionEnumVariant[] {\n const enumVariants: SolanaInstructionEnumVariant[] = [];\n for (const [enumId, variants] of Object.entries(dto.enum_variants ?? {})) {\n for (const [variantIndex, variant] of Object.entries(variants)) {\n const index = Number(variantIndex);\n if (u16Codec.decode(index).isLeft()) {\n continue;\n }\n enumVariants.push({\n enumId,\n variantIndex: index,\n descriptor: {\n data: variant.descriptor.data,\n signature: pickSignature(variant.descriptor.signatures, mode) ?? \"\",\n },\n });\n }\n }\n return enumVariants;\n}\n\n/**\n * Flatten the enum variants of every descriptor in a program into a single\n * list. CAL nests `enum_variants` inside each instruction descriptor but\n * guarantees `(enumId, variantIndex)` is unique across a program, so the enum\n * loader resolves a selection against this program-level list \u2014 independently\n * of whether any individual instruction descriptor carried a usable signature.\n */\nexport function toProgramEnumVariants(\n descriptors: Record<string, CalInstructionDescriptorDto>,\n mode: CalMode,\n): SolanaInstructionEnumVariant[] {\n return Object.values(descriptors).flatMap((dto) => toEnumVariants(dto, mode));\n}\n\n/**\n * Transform one validated CAL descriptor DTO into the core\n * {@link SolanaInstructionInfoPayload}. Returns a `Left` when the descriptor is\n * unusable (no signature for the configured `mode`), so the caller can surface\n * a per-descriptor ERROR rather than emitting an empty signature.\n *\n * `programId` comes from the enclosing `solana_programs` envelope `id`;\n * `discriminator` from the instruction's `discriminator_hex`.\n */\nexport function toInstructionInfoPayload(\n programId: string,\n discriminator: string,\n dto: CalInstructionDescriptorDto,\n mode: CalMode,\n): Either<Error, SolanaInstructionInfoPayload> {\n const signature = pickSignature(dto.descriptor.signatures, mode);\n if (!signature) {\n return Left(\n new Error(\n `[ContextModule] InstructionInfoDataSource: missing '${mode}' signature for (${programId}, ${discriminator})`,\n ),\n );\n }\n\n return Right({\n programId,\n discriminator,\n instructionName: dto.instruction_name,\n instructionInfo: {\n data: dto.descriptor.data,\n signature,\n },\n substructures: toSubstructures(dto),\n enumVariants: toEnumVariants(dto, mode),\n idlDescriptor: {\n typePool: dto.idl_descriptor?.type_pool ?? [],\n rootType: dto.idl_descriptor?.root_type ?? 0,\n },\n mintAssociations: dto.mint_association ? [dto.mint_association] : [],\n ownerAssociations: toOwnerAssociations(dto.owner_association),\n valueFlowPorts: toValueFlowPorts(dto.value_flow_ports),\n accountResets: toAccountResets(dto.account_resets),\n displayFields: toDisplayFields(dto.display_fields),\n hideRules: toHideRules(dto.hide_rules),\n accountSchema: toAccountSchema(dto.account_schema),\n });\n}\n"],
|
|
5
|
+
"mappings": "AAKA,OAAsB,QAAAA,EAAM,SAAAC,MAAa,YAEzC,OAWE,qCAAAC,MACK,wCACP,OAAS,YAAAC,MAAgB,2BAgBzB,SAASC,EACPC,EACAC,EACoB,CACpB,OAAOD,EAAWC,CAAI,CACxB,CAMO,SAASC,EACdC,EAA8B,CAAC,EACL,CAC1B,OAAOA,EAAK,IAAKC,IAAU,CACzB,gBAAiBA,EAAK,gBACtB,0BAA2BA,EAAK,0BAChC,YAAaA,EAAK,YAClB,YAAaA,EAAK,WACpB,EAAE,CACJ,CAEO,SAASC,EACdF,EAA6B,CAAC,EACL,CAGzB,OAAOA,EAAK,QAASG,GACnBA,EAAM,gBAAkB,OACpB,CAAC,EACD,CACE,CACE,cAAeA,EAAM,cACrB,yBAA0BA,EAAM,yBAChC,WAAYA,EAAM,WAClB,MAAOA,EAAM,MACb,gCACEA,EAAM,+BACV,CACF,CACN,CACF,CAUO,SAASC,EAAYJ,EAAyB,CAAC,EAAwB,CAC5E,OAAOA,EAAK,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,EAAI,iBAAiB,EAC5D,eAAgBR,EAAiBQ,EAAI,gBAAgB,EACrD,cAAeL,EAAgBK,EAAI,cAAc,EACjD,cAAeM,EAAgBN,EAAI,cAAc,EACjD,UAAWH,EAAYG,EAAI,UAAU,EACrC,cAAeK,EAAgBL,EAAI,cAAc,CACnD,CAAC,EA5BQf,EACL,IAAI,MACF,uDAAuDM,CAAI,oBAAoB6B,CAAS,KAAKC,CAAa,GAC5G,CACF,CAyBJ",
|
|
6
|
+
"names": ["Left", "Right", "SolanaInstructionSubstructureKind", "u16Codec", "pickSignature", "signatures", "mode", "toValueFlowPorts", "dtos", "port", "toAccountResets", "reset", "toHideRules", "rule", "toOwnerAssociations", "dto", "VALID_CONSTRAINT_VALUES", "toSlotConstraint", "signer", "writable", "toAccountSchema", "toDisplayFields", "field", "toSubstructures", "s", "toEnumVariants", "enumVariants", "enumId", "variants", "variantIndex", "variant", "index", "toProgramEnumVariants", "descriptors", "toInstructionInfoPayload", "programId", "discriminator", "signature"]
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{describe as
|
|
1
|
+
import{describe as o,expect as e,it as t}from"vitest";import{toAccountResets as d,toAccountSchema as c,toDisplayFields as _,toHideRules as l,toInstructionInfoPayload as s,toOwnerAssociations as u,toProgramEnumVariants as m,toValueFlowPorts as p}from"./InstructionInfoMapper";const r="11111111111111111111111111111111";function i(n={}){return{discriminator_hex:"00000000",instruction_name:"createAccount",descriptor:{data:"0001sys_data",signatures:{prod:"prodsig",test:"testsig"}},...n}}o("InstructionInfoMapper",()=>{o("toValueFlowPorts",()=>{t("returns an empty list for undefined input",()=>{e(p()).toEqual([])}),t("picks only the decoded fields, dropping the signed-TLV descriptor",()=>{e(p([{descriptor:"vfp1",account_indices:[0,1],optional_account_strategy:"OMITTED",token_value:{kind:"RESOLVE",fallback_account:5},active_when:["IS_SIGNER"]}])).toEqual([{account_indices:[0,1],optional_account_strategy:"OMITTED",token_value:{kind:"RESOLVE",fallback_account:5},active_when:["IS_SIGNER"]}])}),t("leaves the absent optional strategy as undefined",()=>{e(p([{descriptor:"vfp1",account_indices:[0],token_value:{kind:"NATIVE"}}])).toEqual([{account_indices:[0],optional_account_strategy:void 0,token_value:{kind:"NATIVE"},active_when:void 0}])})}),o("toHideRules",()=>{t("returns an empty list for undefined input",()=>{e(l()).toEqual([])}),t("maps the decoded fields, dropping the signed-TLV descriptor",()=>{e(l([{descriptor:"hr1",rule_set_index:1,target:{source:"ACCOUNT_PATH",account_index:2},condition:"IS_SIGNER"}])).toEqual([{rule_set_index:1,target:{source:"ACCOUNT_PATH",account_index:2},condition:"IS_SIGNER"}])}),t("keeps a rule with no condition so its target stays in the requirement set",()=>{e(l([{descriptor:"hrNoCondition",target:{source:"ACCOUNT_PATH",account_index:4}}])).toEqual([{rule_set_index:void 0,target:{source:"ACCOUNT_PATH",account_index:4},condition:void 0}])})}),o("toOwnerAssociations",()=>{t("returns an empty list for undefined input",()=>{e(u(void 0)).toEqual([])}),t("wraps CAL's single association into a list",()=>{e(u({account_index:1,owner:{source:"ACCOUNT_PATH",account_index:0}})).toEqual([{account_index:1,owner:{source:"ACCOUNT_PATH",account_index:0}}])}),t("drops a half-declared pair",()=>{e(u({account_index:1})).toEqual([]),e(u({owner:{source:"ACCOUNT_PATH"}})).toEqual([])})}),o("toAccountResets",()=>{t("returns an empty list for undefined input",()=>{e(d()).toEqual([])}),t("maps the decoded fields, dropping the signed-TLV descriptor",()=>{e(d([{descriptor:"ar1",account_index:2,require_pre_balance_zero:!0}])).toEqual([{account_index:2,require_pre_balance_zero:!0}])}),t("passes through value_kind, token, and require_native_pre_balance_zero",()=>{e(d([{descriptor:"ar1",account_index:3,value_kind:"splToken",token:{kind:"RESOLVE",account_index:4},require_native_pre_balance_zero:!0}])).toEqual([{account_index:3,value_kind:"splToken",token:{kind:"RESOLVE",account_index:4},require_native_pre_balance_zero:!0}])}),t("drops entries missing account_index instead of defaulting to slot 0",()=>{e(d([{descriptor:"ar0",account_index:0},{descriptor:"arBad"},{descriptor:"ar1",account_index:1}])).toEqual([{account_index:0,require_pre_balance_zero:void 0},{account_index:1,require_pre_balance_zero:void 0}])})}),o("toDisplayFields",()=>{t("returns an empty list for undefined input",()=>{e(_()).toEqual([])}),t("picks name and param, dropping the signed-TLV descriptor",()=>{e(_([{descriptor:"df1",name:"New Account",param:{type:"ACCOUNT",value:{source:"ACCOUNT_PATH",account_index:1}}}])).toEqual([{name:"New Account",param:{type:"ACCOUNT",value:{source:"ACCOUNT_PATH",account_index:1}}}])}),t("falls back to an empty-type param when param is absent",()=>{e(_([{descriptor:"df1"}])).toEqual([{name:void 0,param:{type:""}}])})}),o("toAccountSchema",()=>{t("returns undefined for undefined input (no ACCOUNT_SCHEMA check)",()=>{e(c(void 0)).toBeUndefined()}),t("maps count bounds, remaining_policy, and per-slot constraints",()=>{e(c({count_min:2,count_max:4,remaining_policy:{signer:"FORBIDDEN",writable:"EITHER"},slots:[{signer:"REQUIRED",writable:"EITHER"},{signer:"EITHER",writable:"REQUIRED"}]})).toEqual({count_min:2,count_max:4,remaining_policy:{signer:"FORBIDDEN",writable:"EITHER"},slots:[{signer:"REQUIRED",writable:"EITHER"},{signer:"EITHER",writable:"REQUIRED"}]})}),t("defaults count_min to 0, count_max to 255 (COUNT_UNBOUNDED), remaining_policy and slots to EITHER/empty",()=>{e(c({})).toEqual({count_min:0,count_max:255,remaining_policy:{signer:"EITHER",writable:"EITHER"},slots:[]})}),t("defaults an unknown or missing per-field constraint value to EITHER (fails open, unlike ACCOUNT_RESET's value_kind)",()=>{e(c({count_min:1,count_max:1,remaining_policy:{signer:"NOT_A_VALUE",writable:void 0},slots:[{signer:"REQUIRED"}]})).toEqual({count_min:1,count_max:1,remaining_policy:{signer:"EITHER",writable:"EITHER"},slots:[{signer:"REQUIRED",writable:"EITHER"}]})})}),o("toInstructionInfoPayload",()=>{t("surfaces CAL's decoded JSON (type pool, mint assoc, ports, resets, fields) and ordered substructures",()=>{const n=i({idl_descriptor:{root_type:3,type_pool:[{index:0,kind:"STRUCT",refs:[1]},{index:1,kind:"U64"}]},mint_association:{account_index:1,mint_index:3},owner_association:{account_index:1,owner:{source:"ACCOUNT_PATH",account_index:0}},display_fields:[{descriptor:"df1",name:"New Account",param:{type:"ACCOUNT",value:{source:"ACCOUNT_PATH",account_index:1}}}],value_flow_ports:[{descriptor:"vfp1",account_indices:[0],token_value:{kind:"NATIVE"}}],hide_rules:[{descriptor:"hr1",rule_set_index:0,target:{source:"ACCOUNT_PATH",account_index:1},condition:"ACCOUNT_EFFECTS_DISPLAYED_ELSEWHERE"}],account_resets:[{descriptor:"ar1",account_index:1,require_pre_balance_zero:!0}],account_schema:{count_min:2,count_max:2,slots:[{signer:"REQUIRED",writable:"EITHER"}]}}),a=s(r,"00000000",n,"prod").unsafeCoerce();e(a).toMatchObject({programId:r,discriminator:"00000000",instructionInfo:{data:"0001sys_data",signature:"prodsig"},idlDescriptor:{rootType:3,typePool:[{index:0,kind:"STRUCT",refs:[1]},{index:1,kind:"U64"}]},mintAssociations:[{account_index:1,mint_index:3}],ownerAssociations:[{account_index:1,owner:{source:"ACCOUNT_PATH",account_index:0}}],valueFlowPorts:[{account_indices:[0],optional_account_strategy:void 0,token_value:{kind:"NATIVE"}}],hideRules:[{rule_set_index:0,target:{source:"ACCOUNT_PATH",account_index:1},condition:"ACCOUNT_EFFECTS_DISPLAYED_ELSEWHERE"}],accountResets:[{account_index:1,require_pre_balance_zero:!0}],accountSchema:{count_min:2,count_max:2,remaining_policy:{signer:"EITHER",writable:"EITHER"},slots:[{signer:"REQUIRED",writable:"EITHER"}]},displayFields:[{name:"New Account",param:{type:"ACCOUNT",value:{source:"ACCOUNT_PATH",account_index:1}}}]}),e(a.substructures).toEqual([{kind:0,data:"df1"},{kind:1,data:"vfp1"},{kind:2,data:"hr1"},{kind:3,data:"ar1"}])}),t("defaults idlDescriptor when CAL omits it",()=>{const n=s(r,"00000000",i(),"prod").unsafeCoerce();e(n.idlDescriptor).toEqual({typePool:[],rootType:0}),e(n.mintAssociations).toEqual([])}),t("bundles CAL enum_variants into the payload with the mode signature",()=>{const n=i({enum_variants:{swap:{46:{variant_name:"raydiumCP",descriptor:{data:"01_raydium_tlv",signatures:{prod:"prodsig_v46",test:"testsig_v46"}}}}}}),a=s(r,"00000000",n,"prod").unsafeCoerce();e(a.enumVariants).toEqual([{enumId:"swap",variantIndex:46,descriptor:{data:"01_raydium_tlv",signature:"prodsig_v46"}}])}),t("skips enum_variants keyed by a non-u16 index instead of leaking NaN",()=>{const n=i({enum_variants:{swap:{46:{variant_name:"raydiumCP",descriptor:{data:"01_raydium_tlv",signatures:{prod:"prodsig_v46",test:"testsig_v46"}}},"7abc":{variant_name:"junk",descriptor:{data:"junk_tlv",signatures:{prod:"x",test:"x"}}},7e4:{variant_name:"overflow",descriptor:{data:"overflow_tlv",signatures:{prod:"x",test:"x"}}}}}}),a=s(r,"00000000",n,"prod").unsafeCoerce();e(a.enumVariants).toEqual([{enumId:"swap",variantIndex:46,descriptor:{data:"01_raydium_tlv",signature:"prodsig_v46"}}])}),t("selects the signature for the configured mode",()=>{const n=s(r,"00000000",i(),"test").unsafeCoerce();e(n.instructionInfo.signature).toBe("testsig")}),t("returns Left when the configured mode signature is missing",()=>{const n=i();delete n.descriptor.signatures.test;const a=s(r,"00000000",n,"test");e(a.isLeft()).toBe(!0),e(a.swap().unsafeCoerce().message).toMatch(/missing 'test' signature/)})}),o("toProgramEnumVariants",()=>{t("flattens enum variants across all descriptors, dropping malformed keys",()=>{const n={"00000000":i({enum_variants:{swap:{46:{variant_name:"raydiumCP",descriptor:{data:"01_raydium_tlv",signatures:{prod:"prodsig_v46",test:"testsig_v46"}}},bad:{variant_name:"junk",descriptor:{data:"junk_tlv",signatures:{prod:"x",test:"x"}}}}}}),"00000001":i({enum_variants:{route:{12:{variant_name:"orca",descriptor:{data:"02_orca_tlv",signatures:{prod:"prodsig_v12",test:"testsig_v12"}}}}}})};e(m(n,"prod")).toEqual([{enumId:"swap",variantIndex:46,descriptor:{data:"01_raydium_tlv",signature:"prodsig_v46"}},{enumId:"route",variantIndex:12,descriptor:{data:"02_orca_tlv",signature:"prodsig_v12"}}])}),t("leaves the signature empty when CAL has none for the configured mode",()=>{const n=i({enum_variants:{swap:{46:{variant_name:"raydiumCP",descriptor:{data:"01_raydium_tlv",signatures:{prod:"prodsig_v46"}}}}}});e(m({"00000000":n},"test")).toEqual([{enumId:"swap",variantIndex:46,descriptor:{data:"01_raydium_tlv",signature:""}}])})})});
|
|
2
2
|
//# sourceMappingURL=InstructionInfoMapper.test.js.map
|