@chainlink/cre-sdk 1.13.0 → 1.14.0-solana-alpha-1

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/README.md CHANGED
@@ -237,6 +237,66 @@ const onCronTrigger = (runtime: Runtime<Config>) => {
237
237
  };
238
238
  ```
239
239
 
240
+ ### Solana Write Reports
241
+
242
+ The Solana capability is **write-only**: reports are delivered through the
243
+ keystone-forwarder to a receiver program's `on_report` entrypoint as a bare
244
+ Borsh-encoded struct. The SDK ships the write plumbing under
245
+ `utils/capabilities/blockchain/solana`:
246
+
247
+ - `calculateAccountsHash(accounts)` — sha256 of the concatenated account
248
+ public keys (the forwarder's on-chain account verification),
249
+ - `encodeForwarderReport({ accountHash, payload })` — the
250
+ `[32-byte hash][u32-LE len][payload]` forwarder envelope,
251
+ - `encodeBorshVecU32(elements)` — Borsh `Vec` of pre-encoded elements,
252
+ - `prepareSolanaReportRequest(payload)` — report request with the Solana
253
+ encoder (`solana`/`ecdsa`/`keccak256`),
254
+ - `solanaAccountMeta(publicKey, isWritable)` / `solanaAddressToBytes(base58)`.
255
+
256
+ The wire format is byte-identical to the Go SDK's
257
+ `capabilities/blockchain/solana/bindings` package.
258
+
259
+ Generate typed per-program bindings from an Anchor IDL with the CRE CLI:
260
+
261
+ ```bash
262
+ cre generate-bindings solana --language typescript
263
+ ```
264
+
265
+ ```typescript
266
+ import { cre, type Runtime, solanaAccountMeta, SolanaClient } from "@chainlink/cre-sdk";
267
+ import { DataStorage } from "../contracts/solana/ts/generated";
268
+
269
+ const onTrigger = (runtime: Runtime<Config>) => {
270
+ const client = new SolanaClient(SolanaClient.SUPPORTED_CHAIN_SELECTORS["solana-devnet"]);
271
+ const dataStorage = new DataStorage(client); // program ID baked in from the IDL
272
+
273
+ // remainingAccounts: forwarderState, forwarderAuthority PDA, then receiver accounts
274
+ const remainingAccounts = [
275
+ solanaAccountMeta(forwarderState),
276
+ solanaAccountMeta(forwarderAuthority),
277
+ solanaAccountMeta(receiverDataAccount, true),
278
+ ];
279
+
280
+ const reply = dataStorage.writeReportFromUserData(
281
+ runtime,
282
+ { key: "answer", value: "42" },
283
+ remainingAccounts,
284
+ );
285
+ runtime.log(`tx status: ${reply.txStatus}`);
286
+ };
287
+ ```
288
+
289
+ In tests, intercept writes with the generated mock:
290
+
291
+ ```typescript
292
+ import { SolanaMock } from "@chainlink/cre-sdk/test";
293
+ import { newDataStorageMock } from "../contracts/solana/ts/generated";
294
+
295
+ const solanaMock = SolanaMock.testInstance(chainSelector);
296
+ const dataStorage = newDataStorageMock(solanaMock);
297
+ dataStorage.writeReport = ({ report }) => ({ txStatus: "TX_STATUS_SUCCESS" });
298
+ ```
299
+
240
300
  ## Configuration & Type Safety
241
301
 
242
302
  You, the developer, must declare config files in config.json files, co-located with your TypeScript workflow definition.
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Chain-agnostic core of the per-contract mock routing used by
3
+ * `addContractMock` (EVM) and `addSolanaContractMock` (Solana).
4
+ *
5
+ * Builds a handler that routes a request to `handle` when `matches` returns
6
+ * true, falls through to the previously installed handler otherwise, and
7
+ * throws `noMatchError` when there is nothing to fall through to. Installing
8
+ * the returned handler over the previous one is what lets multiple contract
9
+ * mocks chain on the same capability mock.
10
+ */
11
+ export declare function chainContractHandler<TReq, TReply>(options: {
12
+ previous: ((req: TReq) => TReply) | undefined;
13
+ matches: (req: TReq) => boolean;
14
+ handle: (req: TReq) => TReply;
15
+ noMatchError: (req: TReq) => string;
16
+ }): (req: TReq) => TReply;
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Chain-agnostic core of the per-contract mock routing used by
3
+ * `addContractMock` (EVM) and `addSolanaContractMock` (Solana).
4
+ *
5
+ * Builds a handler that routes a request to `handle` when `matches` returns
6
+ * true, falls through to the previously installed handler otherwise, and
7
+ * throws `noMatchError` when there is nothing to fall through to. Installing
8
+ * the returned handler over the previous one is what lets multiple contract
9
+ * mocks chain on the same capability mock.
10
+ */
11
+ export function chainContractHandler(options) {
12
+ const { previous, matches, handle, noMatchError } = options;
13
+ return (req) => {
14
+ if (!matches(req)) {
15
+ if (previous)
16
+ return previous(req);
17
+ throw new Error(noMatchError(req));
18
+ }
19
+ return handle(req);
20
+ };
21
+ }
@@ -1,4 +1,5 @@
1
1
  import { decodeFunctionData, encodeFunctionResult, } from 'viem';
2
+ import { chainContractHandler } from './contract-mock-core';
2
3
  function bytesToHexAddress(bytes) {
3
4
  return `0x${Array.from(bytes)
4
5
  .map((b) => b.toString(16).padStart(2, '0'))
@@ -49,66 +50,67 @@ export function addContractMock(evmMock, options) {
49
50
  const mock = {};
50
51
  const normalizedAddress = options.address.toLowerCase();
51
52
  const previousCallContract = evmMock.callContract;
52
- evmMock.callContract = (req) => {
53
- const toBytes = req.call?.to;
54
- if (!toBytes || bytesToHexAddress(toBytes) !== normalizedAddress) {
55
- if (previousCallContract)
56
- return previousCallContract(req);
57
- throw new Error(`addContractMock: no mock registered for address ${toBytes ? bytesToHexAddress(toBytes) : '(empty)'}`);
58
- }
59
- const dataBytes = req.call?.data;
60
- if (!dataBytes || dataBytes.length < 4) {
61
- throw new Error('addContractMock: call data too short (need at least 4 bytes for selector)');
62
- }
63
- const callDataHex = bytesToHex(dataBytes);
64
- let decoded;
65
- try {
66
- decoded = decodeFunctionData({
53
+ evmMock.callContract = chainContractHandler({
54
+ previous: previousCallContract,
55
+ matches: (req) => {
56
+ const toBytes = req.call?.to;
57
+ return !!toBytes && bytesToHexAddress(toBytes) === normalizedAddress;
58
+ },
59
+ noMatchError: (req) => `addContractMock: no mock registered for address ${req.call?.to ? bytesToHexAddress(req.call.to) : '(empty)'}`,
60
+ handle: (req) => {
61
+ const dataBytes = req.call?.data;
62
+ if (!dataBytes || dataBytes.length < 4) {
63
+ throw new Error('addContractMock: call data too short (need at least 4 bytes for selector)');
64
+ }
65
+ const callDataHex = bytesToHex(dataBytes);
66
+ let decoded;
67
+ try {
68
+ decoded = decodeFunctionData({
69
+ abi: options.abi,
70
+ data: callDataHex,
71
+ });
72
+ }
73
+ catch (e) {
74
+ if (previousCallContract)
75
+ return previousCallContract(req);
76
+ throw new Error(`addContractMock: failed to decode function data for ${options.address}: ${e instanceof Error ? e.message : e}`);
77
+ }
78
+ const handler = mock[decoded.functionName];
79
+ if (typeof handler !== 'function') {
80
+ throw new Error(`addContractMock: no handler set for ${decoded.functionName} on ${options.address}`);
81
+ }
82
+ const result = handler(...(decoded.args ?? []));
83
+ const encoded = encodeFunctionResult({
67
84
  abi: options.abi,
68
- data: callDataHex,
85
+ functionName: decoded.functionName,
86
+ result: result,
69
87
  });
70
- }
71
- catch (e) {
72
- if (previousCallContract)
73
- return previousCallContract(req);
74
- throw new Error(`addContractMock: failed to decode function data for ${options.address}: ${e instanceof Error ? e.message : e}`);
75
- }
76
- const handler = mock[decoded.functionName];
77
- if (typeof handler !== 'function') {
78
- throw new Error(`addContractMock: no handler set for ${decoded.functionName} on ${options.address}`);
79
- }
80
- const result = handler(...(decoded.args ?? []));
81
- const encoded = encodeFunctionResult({
82
- abi: options.abi,
83
- functionName: decoded.functionName,
84
- result: result,
85
- });
86
- return {
87
- data: hexToUint8Array(encoded),
88
- };
89
- };
88
+ return {
89
+ data: hexToUint8Array(encoded),
90
+ };
91
+ },
92
+ });
90
93
  const previousWriteReport = evmMock.writeReport;
91
- evmMock.writeReport = (req) => {
92
- const receiverBytes = req.receiver;
93
- if (!receiverBytes || bytesToHexAddress(receiverBytes) !== normalizedAddress) {
94
- if (previousWriteReport)
95
- return previousWriteReport(req);
96
- throw new Error(`addContractMock: no writeReport mock registered for receiver ${receiverBytes ? bytesToHexAddress(receiverBytes) : '(empty)'}`);
97
- }
98
- if (typeof mock.writeReport !== 'function') {
99
- throw new Error(`addContractMock: no writeReport handler set for ${options.address}`);
100
- }
101
- if (!req.report) {
102
- throw new Error(`addContractMock: writeReport called without report for ${options.address}`);
103
- }
104
- if (!req.gasConfig) {
105
- throw new Error(`addContractMock: writeReport called without gasConfig for ${options.address}`);
106
- }
107
- return mock.writeReport({
108
- receiver: req.receiver,
109
- report: req.report,
110
- gasConfig: req.gasConfig,
111
- });
112
- };
94
+ evmMock.writeReport = chainContractHandler({
95
+ previous: previousWriteReport,
96
+ matches: (req) => !!req.receiver && bytesToHexAddress(req.receiver) === normalizedAddress,
97
+ noMatchError: (req) => `addContractMock: no writeReport mock registered for receiver ${req.receiver ? bytesToHexAddress(req.receiver) : '(empty)'}`,
98
+ handle: (req) => {
99
+ if (typeof mock.writeReport !== 'function') {
100
+ throw new Error(`addContractMock: no writeReport handler set for ${options.address}`);
101
+ }
102
+ if (!req.report) {
103
+ throw new Error(`addContractMock: writeReport called without report for ${options.address}`);
104
+ }
105
+ if (!req.gasConfig) {
106
+ throw new Error(`addContractMock: writeReport called without gasConfig for ${options.address}`);
107
+ }
108
+ return mock.writeReport({
109
+ receiver: req.receiver,
110
+ report: req.report,
111
+ gasConfig: req.gasConfig,
112
+ });
113
+ },
114
+ });
113
115
  return mock;
114
116
  }
@@ -6,3 +6,4 @@ export { type CapabilityHandler, DEFAULT_MAX_RESPONSE_SIZE_BYTES, getTestCapabil
6
6
  export { TestWriter } from '../testutils/test-writer';
7
7
  export { type AddContractMockOptions, addContractMock, type ContractMock, type WriteReportMockInput, } from './evm-contract-mock';
8
8
  export * from './generated';
9
+ export { type AddSolanaContractMockOptions, addSolanaContractMock, type SolanaContractMock, type SolanaWriteReportMockInput, } from './solana-contract-mock';
@@ -6,3 +6,4 @@ export { DEFAULT_MAX_RESPONSE_SIZE_BYTES, getTestCapabilityHandler, newTestRunti
6
6
  export { TestWriter } from '../testutils/test-writer';
7
7
  export { addContractMock, } from './evm-contract-mock';
8
8
  export * from './generated';
9
+ export { addSolanaContractMock, } from './solana-contract-mock';
@@ -0,0 +1,54 @@
1
+ import type { AccountMeta, ComputeConfig, WriteReportReply, WriteReportReplyJson } from '../../generated/capabilities/blockchain/solana/v1alpha/client_pb';
2
+ import type { ReportResponse } from '../../generated/sdk/v1alpha/sdk_pb';
3
+ import type { SolanaMock } from './generated';
4
+ /**
5
+ * Strict version of {@link WriteReportRequest} where `report` is guaranteed
6
+ * to be present. Used by mock handlers so tests don't need to check for
7
+ * undefined.
8
+ */
9
+ export interface SolanaWriteReportMockInput {
10
+ receiver: Uint8Array;
11
+ report: ReportResponse;
12
+ remainingAccounts: AccountMeta[];
13
+ computeConfig?: ComputeConfig;
14
+ }
15
+ /**
16
+ * A program mock returned by {@link addSolanaContractMock}.
17
+ *
18
+ * The Solana CRE capability is write-only, so the only routable handler is
19
+ * `writeReport`. When set, write-report calls targeting this program's ID are
20
+ * routed here; calls for other receivers chain to previously registered mocks.
21
+ */
22
+ export interface SolanaContractMock {
23
+ writeReport?: (input: SolanaWriteReportMockInput) => WriteReportReply | WriteReportReplyJson;
24
+ }
25
+ export interface AddSolanaContractMockOptions {
26
+ /** The receiver program ID — base58 string or 32 raw bytes. */
27
+ programId: string | Uint8Array;
28
+ }
29
+ /**
30
+ * Registers a typed program mock on a {@link SolanaMock} instance.
31
+ *
32
+ * This is the Solana counterpart of {@link addContractMock}: it intercepts
33
+ * `writeReport` on the provided mock, routing calls by receiver program ID.
34
+ * Multiple programs can be mocked on the same `SolanaMock` — each call to
35
+ * `addSolanaContractMock` chains with the previous handler.
36
+ *
37
+ * @example
38
+ * ```ts
39
+ * const solanaMock = SolanaMock.testInstance(chainSelector);
40
+ *
41
+ * const dataStorage = addSolanaContractMock(solanaMock, {
42
+ * programId: 'ECL8142j2YQAvs9R9geSsRnkVH2wLEi7soJCRyJ74cfL',
43
+ * });
44
+ *
45
+ * dataStorage.writeReport = ({ report, remainingAccounts }) => {
46
+ * return { txSignature: new Uint8Array(64) };
47
+ * };
48
+ * ```
49
+ *
50
+ * @param solanaMock - The `SolanaMock` instance to attach to.
51
+ * @param options - The receiver program ID to route on.
52
+ * @returns A mock object with a settable `writeReport` handler.
53
+ */
54
+ export declare function addSolanaContractMock(solanaMock: SolanaMock, options: AddSolanaContractMockOptions): SolanaContractMock;
@@ -0,0 +1,63 @@
1
+ import { solanaAddressToBytes } from '../utils/capabilities/blockchain/solana/solana-helpers';
2
+ import { chainContractHandler } from './contract-mock-core';
3
+ function bytesEqual(a, b) {
4
+ if (a.length !== b.length)
5
+ return false;
6
+ return a.every((byte, i) => byte === b[i]);
7
+ }
8
+ function describeReceiver(receiver) {
9
+ return receiver ? `0x${Buffer.from(receiver).toString('hex')}` : '(empty)';
10
+ }
11
+ /**
12
+ * Registers a typed program mock on a {@link SolanaMock} instance.
13
+ *
14
+ * This is the Solana counterpart of {@link addContractMock}: it intercepts
15
+ * `writeReport` on the provided mock, routing calls by receiver program ID.
16
+ * Multiple programs can be mocked on the same `SolanaMock` — each call to
17
+ * `addSolanaContractMock` chains with the previous handler.
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * const solanaMock = SolanaMock.testInstance(chainSelector);
22
+ *
23
+ * const dataStorage = addSolanaContractMock(solanaMock, {
24
+ * programId: 'ECL8142j2YQAvs9R9geSsRnkVH2wLEi7soJCRyJ74cfL',
25
+ * });
26
+ *
27
+ * dataStorage.writeReport = ({ report, remainingAccounts }) => {
28
+ * return { txSignature: new Uint8Array(64) };
29
+ * };
30
+ * ```
31
+ *
32
+ * @param solanaMock - The `SolanaMock` instance to attach to.
33
+ * @param options - The receiver program ID to route on.
34
+ * @returns A mock object with a settable `writeReport` handler.
35
+ */
36
+ export function addSolanaContractMock(solanaMock, options) {
37
+ const mock = {};
38
+ const programIdBytes = typeof options.programId === 'string'
39
+ ? solanaAddressToBytes(options.programId)
40
+ : options.programId;
41
+ const programIdLabel = typeof options.programId === 'string' ? options.programId : describeReceiver(options.programId);
42
+ const previousWriteReport = solanaMock.writeReport;
43
+ solanaMock.writeReport = chainContractHandler({
44
+ previous: previousWriteReport,
45
+ matches: (req) => !!req.receiver && bytesEqual(req.receiver, programIdBytes),
46
+ noMatchError: (req) => `addSolanaContractMock: no writeReport mock registered for receiver ${describeReceiver(req.receiver)}`,
47
+ handle: (req) => {
48
+ if (typeof mock.writeReport !== 'function') {
49
+ throw new Error(`addSolanaContractMock: no writeReport handler set for ${programIdLabel}`);
50
+ }
51
+ if (!req.report) {
52
+ throw new Error(`addSolanaContractMock: writeReport called without report for ${programIdLabel}`);
53
+ }
54
+ return mock.writeReport({
55
+ receiver: req.receiver,
56
+ report: req.report,
57
+ remainingAccounts: req.remainingAccounts,
58
+ computeConfig: req.computeConfig,
59
+ });
60
+ },
61
+ });
62
+ return mock;
63
+ }
@@ -1,7 +1,8 @@
1
- import type { CallMsgJson, FilterLogTriggerRequestJson } from '../../../../generated/capabilities/blockchain/evm/v1alpha/client_pb';
2
- import type { ReportRequestJson } from '../../../../generated/sdk/v1alpha/sdk_pb';
3
- import { type BigInt as GeneratedBigInt } from '../../../../generated/values/v1/values_pb';
1
+ import type { CallMsgJson, FilterLogTriggerRequestJson } from '../../../../../generated/capabilities/blockchain/evm/v1alpha/client_pb';
2
+ import type { ReportRequestJson } from '../../../../../generated/sdk/v1alpha/sdk_pb';
3
+ import { type BigInt as GeneratedBigInt } from '../../../../../generated/values/v1/values_pb';
4
4
  import type { Address, Hex } from 'viem';
5
+ import { type ReportEncoder } from '../report-helpers';
5
6
  /**
6
7
  * Protobuf BigInt structure returned by SDK methods (e.g., headerByNumber).
7
8
  * Uses Pick to extract just the data fields from the generated type.
@@ -20,7 +21,7 @@ export type ProtoBigInt = Pick<GeneratedBigInt, 'absVal' | 'sign'>;
20
21
  * @param n - The native bigint, number, or string value.
21
22
  * @returns The protobuf BigInt JSON representation.
22
23
  */
23
- export declare const bigintToProtoBigInt: (n: number | bigint | string) => import("../../../../generated/values/v1/values_pb").BigIntJson;
24
+ export declare const bigintToProtoBigInt: (n: number | bigint | string) => import("../../../../../generated/values/v1/values_pb").BigIntJson;
24
25
  /**
25
26
  * Converts a protobuf BigInt to a native JS bigint.
26
27
  * Use this when extracting bigint values from SDK responses.
@@ -41,7 +42,7 @@ export declare const protoBigIntToBigint: (pb: ProtoBigInt) => bigint;
41
42
  * @param n - The block number.
42
43
  * @returns The protobuf BigInt JSON representation.
43
44
  */
44
- export declare const blockNumber: (n: number | bigint | string) => import("../../../../generated/values/v1/values_pb").BigIntJson;
45
+ export declare const blockNumber: (n: number | bigint | string) => import("../../../../../generated/values/v1/values_pb").BigIntJson;
45
46
  /**
46
47
  * EVM Capability Helper.
47
48
  *
@@ -106,7 +107,7 @@ export declare const EVM_DEFAULT_REPORT_ENCODER: {
106
107
  * @param reportEncoder - The report encoder to be used. Defaults to EVM_DEFAULT_REPORT_ENCODER.
107
108
  * @returns The prepared report request.
108
109
  */
109
- export declare const prepareReportRequest: (hexEncodedPayload: Hex, reportEncoder?: Omit<ReportRequestJson, "encodedPayload">) => ReportRequestJson;
110
+ export declare const prepareReportRequest: (hexEncodedPayload: Hex, reportEncoder?: ReportEncoder) => ReportRequestJson;
110
111
  export interface LogTriggerConfigOptions {
111
112
  /** EVM addresses to monitor — hex strings with 0x prefix (20 bytes each) */
112
113
  addresses: Hex[];
@@ -1,8 +1,9 @@
1
1
  import { create, toJson } from '@bufbuild/protobuf';
2
- import { BigIntSchema } from '../../../../generated/values/v1/values_pb';
3
- import { EVMClient } from '../../../cre';
4
- import { bigintToBytes, bytesToBigint, hexToBase64, hexToBytes } from '../../hex-utils';
5
- import { assertSafeIntegerNumber } from '../../safe-integer';
2
+ import { BigIntSchema } from '../../../../../generated/values/v1/values_pb';
3
+ import { EVMClient } from '../../../../cre';
4
+ import { bigintToBytes, bytesToBigint, hexToBase64, hexToBytes } from '../../../hex-utils';
5
+ import { assertSafeIntegerNumber } from '../../../safe-integer';
6
+ import { prepareReportRequestFromBytes } from '../report-helpers';
6
7
  /**
7
8
  * Converts a native JS bigint to a protobuf BigInt JSON representation.
8
9
  * Use this when passing bigint values to SDK methods.
@@ -126,10 +127,7 @@ export const EVM_DEFAULT_REPORT_ENCODER = {
126
127
  * @param reportEncoder - The report encoder to be used. Defaults to EVM_DEFAULT_REPORT_ENCODER.
127
128
  * @returns The prepared report request.
128
129
  */
129
- export const prepareReportRequest = (hexEncodedPayload, reportEncoder = EVM_DEFAULT_REPORT_ENCODER) => ({
130
- encodedPayload: hexToBase64(hexEncodedPayload),
131
- ...reportEncoder,
132
- });
130
+ export const prepareReportRequest = (hexEncodedPayload, reportEncoder = EVM_DEFAULT_REPORT_ENCODER) => prepareReportRequestFromBytes(hexToBytes(hexEncodedPayload), reportEncoder);
133
131
  /**
134
132
  * Validates a hex string and checks that the decoded bytes have the expected length.
135
133
  */
@@ -0,0 +1,19 @@
1
+ import type { ReportRequestJson } from '../../../../generated/sdk/v1alpha/sdk_pb';
2
+ /**
3
+ * Report-encoder settings for a chain family (everything in a `ReportRequest`
4
+ * except the payload itself). See `EVM_DEFAULT_REPORT_ENCODER` and
5
+ * `SOLANA_DEFAULT_REPORT_ENCODER` for the per-chain defaults.
6
+ */
7
+ export type ReportEncoder = Omit<ReportRequestJson, 'encodedPayload'>;
8
+ /**
9
+ * Chain-agnostic core for building a `ReportRequest` from raw payload bytes.
10
+ *
11
+ * Per-chain wrappers (`prepareReportRequest` for EVM hex payloads,
12
+ * `prepareSolanaReportRequest` for Solana Borsh payloads) delegate here so
13
+ * there is a single payload-assembly path.
14
+ *
15
+ * @param payload - The raw payload bytes to be signed.
16
+ * @param reportEncoder - The report encoder settings to use.
17
+ * @returns The prepared report request.
18
+ */
19
+ export declare const prepareReportRequestFromBytes: (payload: Uint8Array, reportEncoder: ReportEncoder) => ReportRequestJson;
@@ -0,0 +1,16 @@
1
+ import { bytesToBase64 } from '../../hex-utils';
2
+ /**
3
+ * Chain-agnostic core for building a `ReportRequest` from raw payload bytes.
4
+ *
5
+ * Per-chain wrappers (`prepareReportRequest` for EVM hex payloads,
6
+ * `prepareSolanaReportRequest` for Solana Borsh payloads) delegate here so
7
+ * there is a single payload-assembly path.
8
+ *
9
+ * @param payload - The raw payload bytes to be signed.
10
+ * @param reportEncoder - The report encoder settings to use.
11
+ * @returns The prepared report request.
12
+ */
13
+ export const prepareReportRequestFromBytes = (payload, reportEncoder) => ({
14
+ encodedPayload: bytesToBase64(payload),
15
+ ...reportEncoder,
16
+ });
@@ -0,0 +1,101 @@
1
+ import type { AccountMetaJson, ComputeConfigJson } from '../../../../../generated/capabilities/blockchain/solana/v1alpha/client_pb';
2
+ import type { ReportRequestJson } from '../../../../../generated/sdk/v1alpha/sdk_pb';
3
+ import { type ReportEncoder } from '../report-helpers';
4
+ /**
5
+ * An account passed to the Solana capability's `remainingAccounts` list.
6
+ * Build instances with {@link solanaAccountMeta}; generated bindings convert
7
+ * to the capability's protobuf JSON shape internally.
8
+ */
9
+ export interface SolanaAccountMeta {
10
+ publicKey: Uint8Array;
11
+ isWritable: boolean;
12
+ }
13
+ /**
14
+ * Compute settings for a Solana write-report request. Mirrors the
15
+ * capability's `ComputeConfig` protobuf JSON shape.
16
+ */
17
+ export type SolanaComputeConfig = ComputeConfigJson;
18
+ /**
19
+ * The minimal account shape needed by {@link calculateAccountsHash} —
20
+ * only the public key participates in the hash. Structurally compatible
21
+ * with both {@link SolanaAccountMeta} and the capability's protobuf
22
+ * `AccountMeta`.
23
+ */
24
+ export type SolanaAccountInput = Pick<SolanaAccountMeta, 'publicKey'> & Partial<Pick<SolanaAccountMeta, 'isWritable'>>;
25
+ /**
26
+ * Converts a base58-encoded Solana address to its 32 raw bytes.
27
+ *
28
+ * @param base58Address - The base58-encoded address (validated).
29
+ * @returns The 32-byte public key.
30
+ */
31
+ export declare const solanaAddressToBytes: (base58Address: string) => Uint8Array;
32
+ /**
33
+ * Builds an account entry for the Solana capability's `remainingAccounts` list.
34
+ *
35
+ * @param publicKey - The account's public key, as 32 raw bytes or a base58 string.
36
+ * @param isWritable - Whether the account is writable. Defaults to false.
37
+ * @returns The account meta.
38
+ */
39
+ export declare const solanaAccountMeta: (publicKey: Uint8Array | string, isWritable?: boolean) => SolanaAccountMeta;
40
+ /**
41
+ * Converts {@link SolanaAccountMeta} entries to the capability's protobuf
42
+ * JSON `AccountMeta` shape (base64 public keys), as expected by
43
+ * `SolanaClient.writeReport`. Used by generated bindings.
44
+ */
45
+ export declare const solanaAccountMetasToJson: (accounts: ReadonlyArray<SolanaAccountMeta>) => AccountMetaJson[];
46
+ /**
47
+ * Computes the SHA-256 hash of the concatenated public keys of the given
48
+ * accounts, matching the keystone-forwarder's on-chain account hash
49
+ * verification. Nullish entries are skipped; account order matters.
50
+ *
51
+ * Mirrors Go `bindings.CalculateAccountsHash`.
52
+ *
53
+ * @param accounts - The accounts whose public keys are hashed.
54
+ * @returns The 32-byte account hash.
55
+ */
56
+ export declare const calculateAccountsHash: (accounts: ReadonlyArray<SolanaAccountInput | null | undefined>) => Uint8Array;
57
+ export interface ForwarderReport {
58
+ /** The 32-byte hash from `calculateAccountsHash`. */
59
+ accountHash: Uint8Array;
60
+ /** The Borsh-encoded report payload the receiver's `on_report` deserializes. */
61
+ payload: Uint8Array;
62
+ }
63
+ /**
64
+ * Borsh-encodes a `ForwarderReport` for the keystone-forwarder:
65
+ * `[32-byte accountHash][u32-LE payload length][payload bytes]`.
66
+ *
67
+ * Mirrors Go `bindings.ForwarderReport.Marshal`.
68
+ *
69
+ * @param report - The account hash and payload to encode.
70
+ * @returns The encoded forwarder report.
71
+ */
72
+ export declare const encodeForwarderReport: (report: ForwarderReport) => Uint8Array;
73
+ /**
74
+ * Returns the Anchor/Borsh encoding of a Vec whose elements are opaque byte
75
+ * payloads: `[u32-LE element count][concatenated element payloads]`.
76
+ * Each element must already be fully serialized for one Vec item on the wire.
77
+ *
78
+ * Mirrors Go's generated `EncodeBorshVecU32`.
79
+ *
80
+ * @param elementPayloads - The pre-encoded Vec elements.
81
+ * @returns The encoded Vec.
82
+ */
83
+ export declare const encodeBorshVecU32: (elementPayloads: ReadonlyArray<Uint8Array>) => Uint8Array;
84
+ /**
85
+ * Default values expected by the Solana capability for report encoding.
86
+ * Mirrors the constants emitted by the Go Solana bindings generator.
87
+ */
88
+ export declare const SOLANA_DEFAULT_REPORT_ENCODER: {
89
+ encoderName: string;
90
+ signingAlgo: string;
91
+ hashingAlgo: string;
92
+ };
93
+ /**
94
+ * Prepares a report request for the Solana capability to pass to `.report()`.
95
+ * Takes raw bytes (typically an encoded `ForwarderReport`), not hex.
96
+ *
97
+ * @param payload - The encoded payload bytes to be signed.
98
+ * @param reportEncoder - The report encoder to use. Defaults to SOLANA_DEFAULT_REPORT_ENCODER.
99
+ * @returns The prepared report request.
100
+ */
101
+ export declare const prepareSolanaReportRequest: (payload: Uint8Array, reportEncoder?: ReportEncoder) => ReportRequestJson;
@@ -0,0 +1,100 @@
1
+ import { bytesToBase64 } from '../../../hex-utils';
2
+ import { sha256 } from '@noble/hashes/sha2';
3
+ import { concatBytes } from '@noble/hashes/utils';
4
+ import { address, getAddressEncoder } from '@solana/addresses';
5
+ import { prepareReportRequestFromBytes } from '../report-helpers';
6
+ const ACCOUNT_HASH_LENGTH = 32;
7
+ const U32_LENGTH = 4;
8
+ // Stateless address encoder; hoisted so the encoder stack isn't rebuilt per call.
9
+ const ADDRESS_ENCODER = getAddressEncoder();
10
+ /** Encodes a number as a little-endian Borsh u32. */
11
+ const u32LE = (value) => {
12
+ const bytes = new Uint8Array(U32_LENGTH);
13
+ new DataView(bytes.buffer).setUint32(0, value, true);
14
+ return bytes;
15
+ };
16
+ /**
17
+ * Converts a base58-encoded Solana address to its 32 raw bytes.
18
+ *
19
+ * @param base58Address - The base58-encoded address (validated).
20
+ * @returns The 32-byte public key.
21
+ */
22
+ export const solanaAddressToBytes = (base58Address) => new Uint8Array(ADDRESS_ENCODER.encode(address(base58Address)));
23
+ /**
24
+ * Builds an account entry for the Solana capability's `remainingAccounts` list.
25
+ *
26
+ * @param publicKey - The account's public key, as 32 raw bytes or a base58 string.
27
+ * @param isWritable - Whether the account is writable. Defaults to false.
28
+ * @returns The account meta.
29
+ */
30
+ export const solanaAccountMeta = (publicKey, isWritable = false) => ({
31
+ publicKey: typeof publicKey === 'string' ? solanaAddressToBytes(publicKey) : publicKey,
32
+ isWritable,
33
+ });
34
+ /**
35
+ * Converts {@link SolanaAccountMeta} entries to the capability's protobuf
36
+ * JSON `AccountMeta` shape (base64 public keys), as expected by
37
+ * `SolanaClient.writeReport`. Used by generated bindings.
38
+ */
39
+ export const solanaAccountMetasToJson = (accounts) => accounts.map((account) => ({
40
+ publicKey: bytesToBase64(account.publicKey),
41
+ isWritable: account.isWritable,
42
+ }));
43
+ /**
44
+ * Computes the SHA-256 hash of the concatenated public keys of the given
45
+ * accounts, matching the keystone-forwarder's on-chain account hash
46
+ * verification. Nullish entries are skipped; account order matters.
47
+ *
48
+ * Mirrors Go `bindings.CalculateAccountsHash`.
49
+ *
50
+ * @param accounts - The accounts whose public keys are hashed.
51
+ * @returns The 32-byte account hash.
52
+ */
53
+ export const calculateAccountsHash = (accounts) => {
54
+ const publicKeys = accounts.filter((acc) => acc != null).map(({ publicKey }) => publicKey);
55
+ return sha256(concatBytes(...publicKeys));
56
+ };
57
+ /**
58
+ * Borsh-encodes a `ForwarderReport` for the keystone-forwarder:
59
+ * `[32-byte accountHash][u32-LE payload length][payload bytes]`.
60
+ *
61
+ * Mirrors Go `bindings.ForwarderReport.Marshal`.
62
+ *
63
+ * @param report - The account hash and payload to encode.
64
+ * @returns The encoded forwarder report.
65
+ */
66
+ export const encodeForwarderReport = (report) => {
67
+ if (report.accountHash.length !== ACCOUNT_HASH_LENGTH) {
68
+ throw new Error(`encodeForwarderReport: accountHash must be exactly ${ACCOUNT_HASH_LENGTH} bytes, got ${report.accountHash.length}`);
69
+ }
70
+ return concatBytes(report.accountHash, u32LE(report.payload.length), report.payload);
71
+ };
72
+ /**
73
+ * Returns the Anchor/Borsh encoding of a Vec whose elements are opaque byte
74
+ * payloads: `[u32-LE element count][concatenated element payloads]`.
75
+ * Each element must already be fully serialized for one Vec item on the wire.
76
+ *
77
+ * Mirrors Go's generated `EncodeBorshVecU32`.
78
+ *
79
+ * @param elementPayloads - The pre-encoded Vec elements.
80
+ * @returns The encoded Vec.
81
+ */
82
+ export const encodeBorshVecU32 = (elementPayloads) => concatBytes(u32LE(elementPayloads.length), ...elementPayloads);
83
+ /**
84
+ * Default values expected by the Solana capability for report encoding.
85
+ * Mirrors the constants emitted by the Go Solana bindings generator.
86
+ */
87
+ export const SOLANA_DEFAULT_REPORT_ENCODER = {
88
+ encoderName: 'solana',
89
+ signingAlgo: 'ecdsa',
90
+ hashingAlgo: 'keccak256',
91
+ };
92
+ /**
93
+ * Prepares a report request for the Solana capability to pass to `.report()`.
94
+ * Takes raw bytes (typically an encoded `ForwarderReport`), not hex.
95
+ *
96
+ * @param payload - The encoded payload bytes to be signed.
97
+ * @param reportEncoder - The report encoder to use. Defaults to SOLANA_DEFAULT_REPORT_ENCODER.
98
+ * @returns The prepared report request.
99
+ */
100
+ export const prepareSolanaReportRequest = (payload, reportEncoder = SOLANA_DEFAULT_REPORT_ENCODER) => prepareReportRequestFromBytes(payload, reportEncoder);
@@ -13,6 +13,12 @@ export declare const hexToBytes: (hexStr: string) => Uint8Array;
13
13
  * Convert Uint8Array to hex string with 0x prefix
14
14
  */
15
15
  export declare const bytesToHex: (bytes: Uint8Array) => Hex;
16
+ /**
17
+ * Encode raw bytes as base64 string
18
+ * @param bytes
19
+ * @returns
20
+ */
21
+ export declare const bytesToBase64: (bytes: Uint8Array) => string;
16
22
  /**
17
23
  * Encode hex as base64 string
18
24
  * @param hex
@@ -28,6 +28,14 @@ export const bytesToHex = (bytes) => {
28
28
  .map((b) => b.toString(16).padStart(2, '0'))
29
29
  .join('')}`;
30
30
  };
31
+ /**
32
+ * Encode raw bytes as base64 string
33
+ * @param bytes
34
+ * @returns
35
+ */
36
+ export const bytesToBase64 = (bytes) => {
37
+ return Buffer.from(bytes).toString('base64');
38
+ };
31
39
  /**
32
40
  * Encode hex as base64 string
33
41
  * @param hex
@@ -1,4 +1,6 @@
1
- export * from './capabilities/blockchain/blockchain-helpers';
1
+ export * from './capabilities/blockchain/evm/evm-helpers';
2
+ export type { ReportEncoder } from './capabilities/blockchain/report-helpers';
3
+ export * from './capabilities/blockchain/solana/solana-helpers';
2
4
  export * from './capabilities/http/http-helpers';
3
5
  export * from './chain-selectors';
4
6
  export * from './decode-json';
@@ -1,4 +1,5 @@
1
- export * from './capabilities/blockchain/blockchain-helpers';
1
+ export * from './capabilities/blockchain/evm/evm-helpers';
2
+ export * from './capabilities/blockchain/solana/solana-helpers';
2
3
  export * from './capabilities/http/http-helpers';
3
4
  export * from './chain-selectors';
4
5
  export * from './decode-json';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chainlink/cre-sdk",
3
- "version": "1.13.0",
3
+ "version": "1.14.0-solana-alpha-1",
4
4
  "type": "module",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -61,7 +61,10 @@
61
61
  "dependencies": {
62
62
  "@bufbuild/protobuf": "2.6.3",
63
63
  "@bufbuild/protoc-gen-es": "2.6.3",
64
- "@chainlink/cre-sdk-javy-plugin": "1.7.0",
64
+ "@chainlink/cre-sdk-javy-plugin": "1.8.0-solana-alpha-1",
65
+ "@noble/hashes": "1.8.0",
66
+ "@solana/addresses": "6.9.0",
67
+ "@solana/codecs": "6.9.0",
65
68
  "@standard-schema/spec": "1.0.0",
66
69
  "viem": "2.34.0",
67
70
  "zod": "3.25.76"