@ethberry/nestjs-router-solana 0.0.0-stage → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 EthBerry Studio
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,72 @@
1
- # Temporary Holding Version
1
+ # @ethberry/nestjs-router-solana
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Reads Solana slot by slot and hands the transfers of watched addresses to Nest controllers, the way `@ethberry/nestjs-router-eth` hands EVM logs.
4
+
5
+ ## Peers
6
+
7
+ `@nestjs/common`, `@nestjs/core`, `@nestjs/config`, `@nestjs/microservices`, `@nestjs/schedule`, `cron`, `@solana/kit`, `rxjs`.
8
+
9
+ ## Exports
10
+
11
+ - `SolanaModule` (`register` / `registerAsync` with `ISolanaModuleOptions`), `SolanaService`.
12
+ - `SolanaService`: `updateRegistry({ contractType, contractAddress })`, `getRegistry()`, `getLastProcessedSlot()`, `listen()` (one run; the cron calls it).
13
+ - `SolanaEventType.TRANSFER`, `BLOCK_EVENT`, `NATIVE`, `SOLANA_RPC` (the RPC provider token), `getTransfers(tx)`.
14
+ - Types: `ITransfer`, `IBlockEvent`, `ILogEvent`, `IContractOptions`, `ISolanaTransaction`, `ISolanaModuleOptions`.
15
+
16
+ ## Configuration
17
+
18
+ - `SOLANA_RPC_URL`: the JSON-RPC endpoint.
19
+ - Module options (`ISolanaModuleOptions`): `fromSlot` (where to start), `commitment` (`finalized` by default), `chunkSize` (slots per run, default 100; also the most a failed run reads again), `cron`, `debug`. After a failed run the next cron ticks are skipped, doubling up to 15.
20
+
21
+ ## Example
22
+
23
+ ```ts
24
+ @Module({
25
+ imports: [
26
+ SolanaModule.registerAsync({
27
+ imports: [ConfigModule, SettingsModule],
28
+ inject: [SettingsService],
29
+ useFactory: async (settings: SettingsService) => ({
30
+ fromSlot: BigInt(await settings.retrieveByKey("SOLANA_SLOT")) + 1n,
31
+ cron: CronExpression.EVERY_10_SECONDS,
32
+ debug: false,
33
+ }),
34
+ }),
35
+ ],
36
+ controllers: [PaymentController],
37
+ })
38
+ export class PaymentModule {}
39
+
40
+ @Controller()
41
+ export class PaymentController {
42
+ constructor(private readonly solanaService: SolanaService, private readonly settings: SettingsService) {}
43
+
44
+ public onModuleInit() {
45
+ this.solanaService.updateRegistry({ contractType: "MERCHANT", contractAddress: [merchantWallet] });
46
+ }
47
+
48
+ @EventPattern({ contractType: "MERCHANT", eventName: SolanaEventType.TRANSFER })
49
+ public transfer(@Payload() event: ILogEvent<ITransfer>, @Ctx() tx: ISolanaTransaction) {
50
+ // event.args: { slot, signature, owner, asset ("native" or the mint), amount (signed), decimals, memo }
51
+ }
52
+
53
+ // after every handler of the range has finished: save the cursor
54
+ @EventPattern({ eventName: BLOCK_EVENT })
55
+ public block(@Payload() event: ILogEvent<IBlockEvent>) {
56
+ return this.settings.update("SOLANA_SLOT", event.args.slot.toString());
57
+ }
58
+ }
59
+ ```
60
+
61
+ ## Writing handlers
62
+
63
+ - **Each event once.** A handler that throws or rejects is logged and skipped; its event is not delivered again. Handle your own failures (retry inside the handler, an outbox). After a restart before the cursor was saved, the range since the last save comes again: record a payment once per `signature`.
64
+ - A watched address (a wallet, or a Solana Pay reference) makes the reader hand over **every** balance change of each transaction that names it: one `Transfer` per change (the payer's minus, the receiver's plus, the rent of a token account created on the way). For a payment to a merchant, keep `owner === merchant` and the expected `asset`; the same transaction comes as several events.
65
+ - A token payment names the merchant's token account, not always the merchant's wallet; the reader still routes it, because it also matches the owner of a changed token balance.
66
+ - The reference of a payment: the second handler argument is the transaction as `getBlock` returned it; its keys are `transaction.message.accountKeys[].pubkey`. Register the merchants' wallets (few, stable), not one reference per payment.
67
+ - A failed transaction (`meta.err` set) never gives a `Transfer`; a transaction whose RPC left `err` out counts as successful.
68
+ - Amounts are signed base units; `decimals` is 9 for SOL and the mint's for a token. The fee payer's native amount excludes the fee.
69
+ - Save the cursor in the `block` handler: it runs after every transfer handler of the range has finished.
70
+ - When the cursor is older than the node's history, the reader stops with an error instead of skipping slots.
71
+
72
+ How it works, in full: [docs/block-reader.md](docs/block-reader.md).
@@ -0,0 +1,6 @@
1
+ export * from "./interfaces/index.js";
2
+ export * from "./providers/rpc.js";
3
+ export * from "./utils/get-transfers.js";
4
+ export * from "./solana.constants.js";
5
+ export * from "./solana.module.js";
6
+ export * from "./solana.service.js";
package/dist/index.js ADDED
@@ -0,0 +1,7 @@
1
+ export * from "./interfaces/index.js";
2
+ export * from "./providers/rpc.js";
3
+ export * from "./utils/get-transfers.js";
4
+ export * from "./solana.constants.js";
5
+ export * from "./solana.module.js";
6
+ export * from "./solana.service.js";
7
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,uBAAuB,CAAC;AACtC,cAAc,oBAAoB,CAAC;AACnC,cAAc,0BAA0B,CAAC;AACzC,cAAc,uBAAuB,CAAC;AACtC,cAAc,oBAAoB,CAAC;AACnC,cAAc,qBAAqB,CAAC"}
@@ -0,0 +1,71 @@
1
+ import { CronExpression } from "@nestjs/schedule";
2
+ export interface ISolanaModuleOptions {
3
+ fromSlot: bigint;
4
+ commitment?: "confirmed" | "finalized";
5
+ chunkSize?: number;
6
+ debug: boolean;
7
+ cron: CronExpression;
8
+ }
9
+ export interface IContractOptions {
10
+ contractType: string;
11
+ contractAddress: string[];
12
+ }
13
+ export interface ILogEvent<T = any> {
14
+ name: string;
15
+ args: T;
16
+ }
17
+ export interface ITransfer {
18
+ slot: bigint;
19
+ signature: string;
20
+ owner: string;
21
+ asset: string;
22
+ amount: bigint;
23
+ decimals: number;
24
+ memo: string[];
25
+ }
26
+ export interface IBlockEvent {
27
+ slot: bigint;
28
+ }
29
+ type IInstruction = {
30
+ programId: string;
31
+ } | {
32
+ programId: string;
33
+ parsed: unknown;
34
+ };
35
+ export interface ISolanaTransaction {
36
+ transaction: {
37
+ signatures: readonly string[];
38
+ message: {
39
+ accountKeys: ReadonlyArray<{
40
+ pubkey: string;
41
+ }>;
42
+ instructions: readonly IInstruction[];
43
+ };
44
+ };
45
+ meta: {
46
+ err?: unknown;
47
+ fee: bigint | number;
48
+ preBalances: ReadonlyArray<bigint | number>;
49
+ postBalances: ReadonlyArray<bigint | number>;
50
+ preTokenBalances?: readonly ITokenBalance[];
51
+ postTokenBalances?: readonly ITokenBalance[];
52
+ innerInstructions?: ReadonlyArray<{
53
+ instructions: readonly IInstruction[];
54
+ }> | null;
55
+ } | null;
56
+ }
57
+ export interface ITokenBalance {
58
+ mint: string;
59
+ owner?: string;
60
+ uiTokenAmount: {
61
+ amount: string;
62
+ decimals: number;
63
+ };
64
+ }
65
+ export interface IDiscoveredHandler<T> {
66
+ meta: T;
67
+ methodName: string;
68
+ handler: (...args: any[]) => unknown;
69
+ instance: object;
70
+ }
71
+ export {};
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/interfaces/index.ts"],"names":[],"mappings":""}
@@ -0,0 +1,7 @@
1
+ import { ConfigService } from "@nestjs/config";
2
+ import type { Rpc, SolanaRpcApi } from "@solana/kit";
3
+ export declare const solanaRpcProvider: {
4
+ provide: symbol;
5
+ inject: (typeof ConfigService)[];
6
+ useFactory: (configService: ConfigService) => Rpc<SolanaRpcApi>;
7
+ };
@@ -0,0 +1,11 @@
1
+ import { ConfigService } from "@nestjs/config";
2
+ import { createSolanaRpc } from "@solana/kit";
3
+ import { SOLANA_RPC } from "../solana.constants.js";
4
+ export const solanaRpcProvider = {
5
+ provide: SOLANA_RPC,
6
+ inject: [ConfigService],
7
+ useFactory: (configService) => {
8
+ return createSolanaRpc(configService.get("SOLANA_RPC_URL", "http://localhost:8899"));
9
+ },
10
+ };
11
+ //# sourceMappingURL=rpc.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rpc.js","sourceRoot":"","sources":["../../src/providers/rpc.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAC/C,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAG9C,OAAO,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AAEpD,MAAM,CAAC,MAAM,iBAAiB,GAAG;IAC/B,OAAO,EAAE,UAAU;IACnB,MAAM,EAAE,CAAC,aAAa,CAAC;IACvB,UAAU,EAAE,CAAC,aAA4B,EAAqB,EAAE;QAC9D,OAAO,eAAe,CAAC,aAAa,CAAC,GAAG,CAAS,gBAAgB,EAAE,uBAAuB,CAAC,CAAC,CAAC;IAC/F,CAAC;CACF,CAAC"}
@@ -0,0 +1,6 @@
1
+ export declare const SOLANA_RPC: unique symbol;
2
+ export declare const BLOCK_EVENT = "block";
3
+ export declare const NATIVE = "native";
4
+ export declare enum SolanaEventType {
5
+ TRANSFER = "Transfer"
6
+ }
@@ -0,0 +1,9 @@
1
+ export const SOLANA_RPC = Symbol("SOLANA_RPC");
2
+ export const BLOCK_EVENT = "block";
3
+ // the asset of a native SOL transfer (a token transfer has its mint there)
4
+ export const NATIVE = "native";
5
+ export var SolanaEventType;
6
+ (function (SolanaEventType) {
7
+ SolanaEventType["TRANSFER"] = "Transfer";
8
+ })(SolanaEventType || (SolanaEventType = {}));
9
+ //# sourceMappingURL=solana.constants.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"solana.constants.js","sourceRoot":"","sources":["../src/solana.constants.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,UAAU,GAAG,MAAM,CAAC,YAAY,CAAC,CAAC;AAC/C,MAAM,CAAC,MAAM,WAAW,GAAG,OAAO,CAAC;AACnC,2EAA2E;AAC3E,MAAM,CAAC,MAAM,MAAM,GAAG,QAAQ,CAAC;AAE/B,MAAM,CAAN,IAAY,eAEX;AAFD,WAAY,eAAe;IACzB,wCAAqB,CAAA;AACvB,CAAC,EAFW,eAAe,KAAf,eAAe,QAE1B"}
@@ -0,0 +1,2 @@
1
+ import { ISolanaModuleOptions } from "./interfaces/index.js";
2
+ export declare const ConfigurableModuleClass: import("@nestjs/common").ConfigurableModuleCls<ISolanaModuleOptions, "register", "create", {}>, MODULE_OPTIONS_TOKEN: string | symbol;
@@ -0,0 +1,3 @@
1
+ import { ConfigurableModuleBuilder } from "@nestjs/common";
2
+ export const { ConfigurableModuleClass, MODULE_OPTIONS_TOKEN } = new ConfigurableModuleBuilder().build();
3
+ //# sourceMappingURL=solana.module-definition.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"solana.module-definition.js","sourceRoot":"","sources":["../src/solana.module-definition.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,yBAAyB,EAAE,MAAM,gBAAgB,CAAC;AAI3D,MAAM,CAAC,MAAM,EAAE,uBAAuB,EAAE,oBAAoB,EAAE,GAC5D,IAAI,yBAAyB,EAAwB,CAAC,KAAK,EAAE,CAAC"}
@@ -0,0 +1,9 @@
1
+ import { OnModuleDestroy, OnModuleInit } from "@nestjs/common";
2
+ import { SolanaService } from "./solana.service.js";
3
+ import { ConfigurableModuleClass } from "./solana.module-definition.js";
4
+ export declare class SolanaModule extends ConfigurableModuleClass implements OnModuleInit, OnModuleDestroy {
5
+ private readonly solanaService;
6
+ constructor(solanaService: SolanaService);
7
+ onModuleInit(): void;
8
+ onModuleDestroy(): void;
9
+ }
@@ -0,0 +1,39 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ import { Logger, Module } from "@nestjs/common";
11
+ import { ConfigModule } from "@nestjs/config";
12
+ import { DiscoveryModule } from "@nestjs/core";
13
+ import { ScheduleModule } from "@nestjs/schedule";
14
+ import { solanaRpcProvider } from "./providers/rpc.js";
15
+ import { SolanaService } from "./solana.service.js";
16
+ import { ConfigurableModuleClass } from "./solana.module-definition.js";
17
+ let SolanaModule = class SolanaModule extends ConfigurableModuleClass {
18
+ solanaService;
19
+ constructor(solanaService) {
20
+ super();
21
+ this.solanaService = solanaService;
22
+ }
23
+ onModuleInit() {
24
+ return this.solanaService.init();
25
+ }
26
+ onModuleDestroy() {
27
+ return this.solanaService.destroy();
28
+ }
29
+ };
30
+ SolanaModule = __decorate([
31
+ Module({
32
+ imports: [ConfigModule, DiscoveryModule, ScheduleModule.forRoot()],
33
+ providers: [solanaRpcProvider, Logger, SolanaService],
34
+ exports: [SolanaService],
35
+ }),
36
+ __metadata("design:paramtypes", [SolanaService])
37
+ ], SolanaModule);
38
+ export { SolanaModule };
39
+ //# sourceMappingURL=solana.module.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"solana.module.js","sourceRoot":"","sources":["../src/solana.module.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,EAAiC,MAAM,gBAAgB,CAAC;AAC/E,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAC/C,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAElD,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,uBAAuB,EAAE,MAAM,+BAA+B,CAAC;AAOjE,IAAM,YAAY,GAAlB,MAAM,YAAa,SAAQ,uBAAuB;IAC1B;IAA7B,YAA6B,aAA4B;QACvD,KAAK,EAAE,CAAC;QADmB,kBAAa,GAAb,aAAa,CAAe;IAEzD,CAAC;IAEM,YAAY;QACjB,OAAO,IAAI,CAAC,aAAa,CAAC,IAAI,EAAE,CAAC;IACnC,CAAC;IAEM,eAAe;QACpB,OAAO,IAAI,CAAC,aAAa,CAAC,OAAO,EAAE,CAAC;IACtC,CAAC;CACF,CAAA;AAZY,YAAY;IALxB,MAAM,CAAC;QACN,OAAO,EAAE,CAAC,YAAY,EAAE,eAAe,EAAE,cAAc,CAAC,OAAO,EAAE,CAAC;QAClE,SAAS,EAAE,CAAC,iBAAiB,EAAE,MAAM,EAAE,aAAa,CAAC;QACrD,OAAO,EAAE,CAAC,aAAa,CAAC;KACzB,CAAC;qCAE4C,aAAa;GAD9C,YAAY,CAYxB"}
@@ -0,0 +1,41 @@
1
+ import type { LoggerService } from "@nestjs/common";
2
+ import { DiscoveryService, MetadataScanner, Reflector } from "@nestjs/core";
3
+ import { SchedulerRegistry } from "@nestjs/schedule";
4
+ import type { Rpc, SolanaRpcApi } from "@solana/kit";
5
+ import type { IContractOptions, IDiscoveredHandler, ILogEvent, ISolanaModuleOptions } from "./interfaces/index.js";
6
+ interface IRoutedEvent {
7
+ pattern: Record<string, string>;
8
+ description: ILogEvent;
9
+ context: unknown;
10
+ }
11
+ export declare class SolanaService {
12
+ protected readonly loggerService: LoggerService;
13
+ protected readonly rpc: Rpc<SolanaRpcApi>;
14
+ protected readonly discoveryService: DiscoveryService;
15
+ protected readonly metadataScanner: MetadataScanner;
16
+ protected readonly reflector: Reflector;
17
+ protected options: ISolanaModuleOptions;
18
+ protected schedulerRegistry: SchedulerRegistry;
19
+ private instanceId;
20
+ private job?;
21
+ private running;
22
+ private destroyed;
23
+ private failures;
24
+ private skippedTicks;
25
+ private lastProcessedSlot;
26
+ private registry;
27
+ constructor(loggerService: LoggerService, rpc: Rpc<SolanaRpcApi>, discoveryService: DiscoveryService, metadataScanner: MetadataScanner, reflector: Reflector, options: ISolanaModuleOptions, schedulerRegistry: SchedulerRegistry);
28
+ init(): void;
29
+ listen(): Promise<void>;
30
+ updateRegistry(contract: IContractOptions): void;
31
+ getRegistry(): IContractOptions[];
32
+ getLastProcessedSlot(): bigint;
33
+ destroy(): void;
34
+ protected getHandlerByPattern<T extends Array<Record<string, string>>>(route: string): Array<IDiscoveredHandler<T>>;
35
+ protected call({ pattern, description, context }: IRoutedEvent): Promise<void>;
36
+ private hasHandler;
37
+ private notRead;
38
+ private readRange;
39
+ private route;
40
+ }
41
+ export {};
@@ -0,0 +1,282 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
11
+ return function (target, key) { decorator(target, key, paramIndex); }
12
+ };
13
+ var SolanaService_1;
14
+ import { Inject, Injectable, Logger } from "@nestjs/common";
15
+ import { DiscoveryService, MetadataScanner, Reflector } from "@nestjs/core";
16
+ import { transformPatternToRoute } from "@nestjs/microservices/utils/index.js";
17
+ import { PATTERN_METADATA } from "@nestjs/microservices/constants";
18
+ import { SchedulerRegistry } from "@nestjs/schedule";
19
+ import { CronJob } from "cron";
20
+ import { getTransfers } from "./utils/get-transfers.js";
21
+ import { BLOCK_EVENT, SOLANA_RPC, SolanaEventType } from "./solana.constants.js";
22
+ import { MODULE_OPTIONS_TOKEN } from "./solana.module-definition.js";
23
+ const blockPattern = { eventName: BLOCK_EVENT };
24
+ // slots per run: about 40 s of chain, also the most a failed run reads again
25
+ const DEFAULT_CHUNK_SIZE = 100;
26
+ // the longest pause after failed runs, in cron ticks
27
+ // (a node outage is retried at least every 16 ticks once it is over)
28
+ const MAX_SKIPPED_TICKS = 15;
29
+ let SolanaService = SolanaService_1 = class SolanaService {
30
+ loggerService;
31
+ rpc;
32
+ discoveryService;
33
+ metadataScanner;
34
+ reflector;
35
+ options;
36
+ schedulerRegistry;
37
+ instanceId = (Math.random() + 1).toString(36).substring(7);
38
+ job;
39
+ running = false;
40
+ destroyed = false;
41
+ // failed runs in a row, and the cron ticks still to skip after them
42
+ failures = 0;
43
+ skippedTicks = 0;
44
+ lastProcessedSlot = -1n;
45
+ registry = [];
46
+ constructor(loggerService, rpc, discoveryService, metadataScanner, reflector, options, schedulerRegistry) {
47
+ this.loggerService = loggerService;
48
+ this.rpc = rpc;
49
+ this.discoveryService = discoveryService;
50
+ this.metadataScanner = metadataScanner;
51
+ this.reflector = reflector;
52
+ this.options = options;
53
+ this.schedulerRegistry = schedulerRegistry;
54
+ }
55
+ // A run per cron tick. After a failed run the next ones are skipped, doubling (1, 3, 7… up to MAX_SKIPPED_TICKS
56
+ // ticks), so a handler that keeps failing on one event does not hammer the node; every failure is logged with its
57
+ // count. A successful run resets it.
58
+ init() {
59
+ this.job = new CronJob(this.options.cron, async () => {
60
+ // a run the app started itself is still going: not a run of this tick, it changes nothing
61
+ if (this.running) {
62
+ return;
63
+ }
64
+ if (this.skippedTicks > 0) {
65
+ this.skippedTicks--;
66
+ return;
67
+ }
68
+ await this.listen().then(() => {
69
+ this.failures = 0;
70
+ }, (e) => {
71
+ this.failures++;
72
+ this.skippedTicks = Math.min(2 ** this.failures - 1, MAX_SKIPPED_TICKS);
73
+ this.loggerService.error(`Run failed ${this.failures} time(s) in a row, next try in ${this.skippedTicks + 1} tick(s): ${String(e)}`, `${SolanaService_1.name}-${this.instanceId}`);
74
+ });
75
+ });
76
+ this.schedulerRegistry.addCronJob(`solanaListener_${this.instanceId}`, this.job);
77
+ this.job.start();
78
+ }
79
+ // Reads the next range of slots up to the head at the commitment and hands every transfer to the handlers, one at a
80
+ // time in chain order. The whole range is read before any handler runs, so a node error delivers nothing and the next
81
+ // run reads the same range again. Each event is delivered once: a handler that fails is logged and the run goes on
82
+ // (what to do with an event it could not handle is the handler's business; `signature` identifies it). Only one run
83
+ // at a time: a call while a run is going returns at once.
84
+ async listen() {
85
+ if (this.running) {
86
+ return;
87
+ }
88
+ this.running = true;
89
+ try {
90
+ if (!this.registry.length) {
91
+ return;
92
+ }
93
+ const commitment = this.options.commitment ?? "finalized";
94
+ const head = await this.rpc.getSlot({ commitment }).send();
95
+ const fromSlot = this.options.fromSlot;
96
+ if (fromSlot > head) {
97
+ return;
98
+ }
99
+ const chunkSize = BigInt(this.options.chunkSize ?? DEFAULT_CHUNK_SIZE);
100
+ const toSlot = head < fromSlot + chunkSize - 1n ? head : fromSlot + chunkSize - 1n;
101
+ // only the slots that have a block: a leader may skip its slot
102
+ const slots = await this.rpc.getBlocks(fromSlot, toSlot, { commitment }).send();
103
+ // A node that keeps only recent blocks answers getBlocks below its first one from that first one, silently. A node
104
+ // with full history (a BigTable-backed provider) returns the older slots; then nothing is missing.
105
+ const firstAvailable = await this.rpc.getFirstAvailableBlock().send();
106
+ if (fromSlot < firstAvailable && !(slots.length && slots[0] < firstAvailable)) {
107
+ throw new Error(`Slots ${fromSlot}..${firstAvailable - 1n} are no longer on the node: reading stops here. Read them from a node ` +
108
+ `with full history, or move the cursor (fromSlot) on purpose.`);
109
+ }
110
+ // A handler can add to the registry while the range is processed (a deploy adds a new address): after a pass and all
111
+ // its handlers, the range is read again for the addresses that appeared during it, until none appears. A
112
+ // transaction goes to a contract type once per range, also when it names several of its addresses.
113
+ const read = new Set();
114
+ const delivered = new Set();
115
+ let pass = this.notRead(read);
116
+ while (pass.length) {
117
+ const events = await this.readRange(slots, commitment, pass, delivered);
118
+ for (const event of events) {
119
+ if (this.destroyed) {
120
+ return;
121
+ }
122
+ await this.call(event);
123
+ }
124
+ pass = this.notRead(read);
125
+ }
126
+ if (this.destroyed) {
127
+ return;
128
+ }
129
+ const args = { slot: toSlot };
130
+ const blockEvent = { pattern: blockPattern, description: { name: BLOCK_EVENT, args }, context: args };
131
+ if (this.hasHandler(blockPattern)) {
132
+ await this.call(blockEvent);
133
+ }
134
+ this.lastProcessedSlot = toSlot;
135
+ this.options.fromSlot = toSlot + 1n;
136
+ }
137
+ finally {
138
+ this.running = false;
139
+ }
140
+ }
141
+ updateRegistry(contract) {
142
+ const entry = this.registry.find(e => e.contractType === contract.contractType);
143
+ if (entry) {
144
+ entry.contractAddress = [...new Set([...entry.contractAddress, ...contract.contractAddress])];
145
+ }
146
+ else {
147
+ this.registry.push(contract);
148
+ }
149
+ this.loggerService.log(`Solana listener updated: ${contract.contractAddress.join(", ")}`, `${SolanaService_1.name}-${this.instanceId}`);
150
+ }
151
+ getRegistry() {
152
+ return this.registry;
153
+ }
154
+ // the last slot whose transfers have all been handled, -1 before the first range
155
+ getLastProcessedSlot() {
156
+ return this.lastProcessedSlot;
157
+ }
158
+ // Stops the cron job; a run in progress stops before its next handler and does not move the cursor
159
+ destroy() {
160
+ this.destroyed = true;
161
+ if (this.job) {
162
+ void this.job.stop();
163
+ this.schedulerRegistry.deleteCronJob(`solanaListener_${this.instanceId}`);
164
+ }
165
+ }
166
+ getHandlerByPattern(route) {
167
+ const methods = [];
168
+ for (const wrapper of this.discoveryService.getControllers()) {
169
+ const instance = wrapper.instance;
170
+ if (!instance || typeof instance !== "object") {
171
+ continue;
172
+ }
173
+ const prototype = Object.getPrototypeOf(instance);
174
+ for (const methodName of this.metadataScanner.getAllMethodNames(prototype)) {
175
+ const handler = prototype[methodName];
176
+ if (typeof handler !== "function") {
177
+ continue;
178
+ }
179
+ const meta = this.reflector.get(PATTERN_METADATA, handler);
180
+ if (meta) {
181
+ methods.push({ meta, methodName, handler: handler, instance });
182
+ }
183
+ }
184
+ }
185
+ return methods.filter(method => method.meta.some(meta => transformPatternToRoute(meta) === route));
186
+ }
187
+ // Runs every handler of the event. A handler that throws (also synchronously) or rejects is logged and does not stop
188
+ // the others or the run.
189
+ async call({ pattern, description, context }) {
190
+ const route = transformPatternToRoute(pattern);
191
+ const handlers = this.getHandlerByPattern(route);
192
+ if (!handlers.length) {
193
+ this.loggerService.log(`Handler not found for: ${route}`, `${SolanaService_1.name}-${this.instanceId}`);
194
+ return;
195
+ }
196
+ const results = await Promise.allSettled(handlers.map(({ handler, instance }) => Promise.resolve().then(() => handler.bind(instance)(description, context))));
197
+ for (const result of results) {
198
+ if (result.status === "rejected") {
199
+ this.loggerService.error(result.reason, `${SolanaService_1.name}-${this.instanceId}`);
200
+ }
201
+ }
202
+ }
203
+ hasHandler(pattern) {
204
+ return this.getHandlerByPattern(transformPatternToRoute(pattern)).length > 0;
205
+ }
206
+ // the part of the registry this range has not read yet: per entry, its addresses not read; marks them read
207
+ notRead(read) {
208
+ const pass = [];
209
+ for (const entry of this.registry) {
210
+ const contractAddress = entry.contractAddress.filter(address => !read.has(`${entry.contractType} ${address}`));
211
+ contractAddress.forEach(address => read.add(`${entry.contractType} ${address}`));
212
+ if (contractAddress.length) {
213
+ pass.push({ ...entry, contractAddress });
214
+ }
215
+ }
216
+ return pass;
217
+ }
218
+ // The events of the given slots for the given part of the registry, in chain order. A slot listed by getBlocks
219
+ // whose block the node does not return is an error: skipping it would lose its transfers.
220
+ async readRange(slots, commitment, registry, delivered) {
221
+ const events = [];
222
+ for (const slot of slots) {
223
+ const block = await this.rpc
224
+ .getBlock(slot, {
225
+ commitment,
226
+ encoding: "jsonParsed",
227
+ transactionDetails: "full",
228
+ maxSupportedTransactionVersion: 0,
229
+ rewards: false,
230
+ })
231
+ .send();
232
+ if (!block) {
233
+ throw new Error(`Block ${slot} is not available on the node`);
234
+ }
235
+ for (const tx of block.transactions) {
236
+ events.push(...this.route(slot, tx, registry, delivered));
237
+ }
238
+ }
239
+ return events;
240
+ }
241
+ // A transaction that names a watched address (any account key, or the owner of a token balance it changes) goes,
242
+ // with all its transfers, to the handlers of that address's contractType: once per contractType and range
243
+ route(slot, tx, registry, delivered) {
244
+ const transfers = getTransfers(tx);
245
+ if (!transfers.length) {
246
+ return [];
247
+ }
248
+ const named = new Set([
249
+ ...tx.transaction.message.accountKeys.map(key => key.pubkey),
250
+ ...transfers.map(t => t.owner),
251
+ ]);
252
+ const signature = tx.transaction.signatures[0];
253
+ const events = [];
254
+ for (const entry of registry) {
255
+ const key = `${entry.contractType} ${signature}`;
256
+ if (delivered.has(key) || !entry.contractAddress.some(address => named.has(address))) {
257
+ continue;
258
+ }
259
+ delivered.add(key);
260
+ for (const transfer of transfers) {
261
+ const args = { ...transfer, slot, signature };
262
+ events.push({
263
+ pattern: { contractType: entry.contractType, eventName: SolanaEventType.TRANSFER },
264
+ description: { name: SolanaEventType.TRANSFER, args },
265
+ context: tx,
266
+ });
267
+ }
268
+ }
269
+ return events;
270
+ }
271
+ };
272
+ SolanaService = SolanaService_1 = __decorate([
273
+ Injectable(),
274
+ __param(0, Inject(Logger)),
275
+ __param(1, Inject(SOLANA_RPC)),
276
+ __param(5, Inject(MODULE_OPTIONS_TOKEN)),
277
+ __metadata("design:paramtypes", [Object, Object, DiscoveryService,
278
+ MetadataScanner,
279
+ Reflector, Object, SchedulerRegistry])
280
+ ], SolanaService);
281
+ export { SolanaService };
282
+ //# sourceMappingURL=solana.service.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"solana.service.js","sourceRoot":"","sources":["../src/solana.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAE5D,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAE5E,OAAO,EAAE,uBAAuB,EAAE,MAAM,sCAAsC,CAAC;AAC/E,OAAO,EAAE,gBAAgB,EAAE,MAAM,iCAAiC,CAAC;AACnE,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAErD,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAE/B,OAAO,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AACxD,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACjF,OAAO,EAAE,oBAAoB,EAAE,MAAM,+BAA+B,CAAC;AAWrE,MAAM,YAAY,GAAG,EAAE,SAAS,EAAE,WAAW,EAAE,CAAC;AAChD,6EAA6E;AAC7E,MAAM,kBAAkB,GAAG,GAAG,CAAC;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E,CAAC;YAC7B,MAAM,GAAG,GAAG,GAAG,KAAK,CAAC,YAAY,IAAI,SAAS,EAAE,CAAC;YACjD,IAAI,SAAS,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,eAAe,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC;gBACrF,SAAS;YACX,CAAC;YACD,SAAS,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;YACnB,KAAK,MAAM,QAAQ,IAAI,SAAS,EAAE,CAAC;gBACjC,MAAM,IAAI,GAAc,EAAE,GAAG,QAAQ,EAAE,IAAI,EAAE,SAAS,EAAE,CAAC;gBACzD,MAAM,CAAC,IAAI,CAAC;oBACV,OAAO,EAAE,EAAE,YAAY,EAAE,KAAK,CAAC,YAAY,EAAE,SAAS,EAAE,eAAe,CAAC,QAAQ,EAAE;oBAClF,WAAW,EAAE,EAAE,IAAI,EAAE,eAAe,CAAC,QAAQ,EAAE,IAAI,EAAE;oBACrD,OAAO,EAAE,EAAE;iBACZ,CAAC,CAAC;YACL,CAAC;QACH,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;CACF,CAAA;AA7RY,aAAa;IADzB,UAAU,EAAE;IAaR,WAAA,MAAM,CAAC,MAAM,CAAC,CAAA;IAEd,WAAA,MAAM,CAAC,UAAU,CAAC,CAAA;IAKlB,WAAA,MAAM,CAAC,oBAAoB,CAAC,CAAA;qDAHQ,gBAAgB;QACjB,eAAe;QACrB,SAAS,UAGV,iBAAiB;GArBrC,aAAa,CA6RzB"}
@@ -0,0 +1,2 @@
1
+ import type { ISolanaTransaction, ITransfer } from "../interfaces/index.js";
2
+ export declare function getTransfers(tx: ISolanaTransaction): Array<Omit<ITransfer, "slot" | "signature">>;
@@ -0,0 +1,58 @@
1
+ import { NATIVE } from "../solana.constants.js";
2
+ // the SPL Memo program, its current version and the first one
3
+ const MEMO_PROGRAMS = ["MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr", "Memo1UhkJRfHyvLMcVucJwxXeuD728EqVDDwQDxFMNo"];
4
+ const SOL_DECIMALS = 9;
5
+ // Every balance change of one successful transaction: native SOL per account, SPL tokens per (owner, mint).
6
+ // Amounts come from the balances before and after the transaction, never from its instructions: a Token-2022 transfer
7
+ // fee, several transfers in one transaction or an extra account (a Solana Pay reference) make the instructions lie.
8
+ // The fee is not a transfer: it is added back to the fee payer (account 0). A failed transaction moved nothing.
9
+ export function getTransfers(tx) {
10
+ const { meta, transaction } = tx;
11
+ // `err` is null for a successful transaction; an RPC may leave it out, which is not a failure
12
+ const failed = meta?.err !== null && meta?.err !== undefined;
13
+ if (!meta || failed) {
14
+ return [];
15
+ }
16
+ const keys = transaction.message.accountKeys.map(key => key.pubkey);
17
+ // memos of the transaction's own instructions and of instructions called by programs (CPI), in order
18
+ const instructions = [
19
+ ...transaction.message.instructions,
20
+ ...(meta.innerInstructions ?? []).flatMap(inner => inner.instructions),
21
+ ];
22
+ const memo = instructions.flatMap(instruction => MEMO_PROGRAMS.includes(instruction.programId) && "parsed" in instruction ? [String(instruction.parsed)] : []);
23
+ const transfers = [];
24
+ keys.forEach((owner, index) => {
25
+ const fee = index === 0 ? BigInt(meta.fee) : 0n;
26
+ const amount = BigInt(meta.postBalances[index]) - BigInt(meta.preBalances[index]) + fee;
27
+ if (amount !== 0n) {
28
+ transfers.push({ owner, asset: NATIVE, amount, decimals: SOL_DECIMALS, memo });
29
+ }
30
+ });
31
+ // a token account created in this transaction has no "pre" entry; one closed in it has no "post" entry
32
+ const tokens = new Map();
33
+ const add = (balances, sign) => {
34
+ for (const balance of balances ?? []) {
35
+ if (!balance.owner) {
36
+ continue;
37
+ }
38
+ const key = `${balance.owner} ${balance.mint}`;
39
+ const entry = tokens.get(key) ?? {
40
+ owner: balance.owner,
41
+ asset: balance.mint,
42
+ amount: 0n,
43
+ decimals: balance.uiTokenAmount.decimals,
44
+ };
45
+ entry.amount += sign * BigInt(balance.uiTokenAmount.amount);
46
+ tokens.set(key, entry);
47
+ }
48
+ };
49
+ add(meta.preTokenBalances, -1n);
50
+ add(meta.postTokenBalances, 1n);
51
+ for (const entry of tokens.values()) {
52
+ if (entry.amount !== 0n) {
53
+ transfers.push({ ...entry, memo });
54
+ }
55
+ }
56
+ return transfers;
57
+ }
58
+ //# sourceMappingURL=get-transfers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"get-transfers.js","sourceRoot":"","sources":["../../src/utils/get-transfers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,wBAAwB,CAAC;AAGhD,8DAA8D;AAC9D,MAAM,aAAa,GAAG,CAAC,6CAA6C,EAAE,6CAA6C,CAAC,CAAC;AACrH,MAAM,YAAY,GAAG,CAAC,CAAC;AAEvB,4GAA4G;AAC5G,sHAAsH;AACtH,oHAAoH;AACpH,gHAAgH;AAChH,MAAM,UAAU,YAAY,CAAC,EAAsB;IACjD,MAAM,EAAE,IAAI,EAAE,WAAW,EAAE,GAAG,EAAE,CAAC;IACjC,8FAA8F;IAC9F,MAAM,MAAM,GAAG,IAAI,EAAE,GAAG,KAAK,IAAI,IAAI,IAAI,EAAE,GAAG,KAAK,SAAS,CAAC;IAC7D,IAAI,CAAC,IAAI,IAAI,MAAM,EAAE,CAAC;QACpB,OAAO,EAAE,CAAC;IACZ,CAAC;IAED,MAAM,IAAI,GAAG,WAAW,CAAC,OAAO,CAAC,WAAW,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IACpE,qGAAqG;IACrG,MAAM,YAAY,GAAG;QACnB,GAAG,WAAW,CAAC,OAAO,CAAC,YAAY;QACnC,GAAG,CAAC,IAAI,CAAC,iBAAiB,IAAI,EAAE,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,KAAK,CAAC,YAAY,CAAC;KACvE,CAAC;IACF,MAAM,IA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G,CAAC,IAAI;gBAC/B,KAAK,EAAE,OAAO,CAAC,KAAK;gBACpB,KAAK,EAAE,OAAO,CAAC,IAAI;gBACnB,MAAM,EAAE,EAAE;gBACV,QAAQ,EAAE,OAAO,CAAC,aAAa,CAAC,QAAQ;aACzC,CAAC;YACF,KAAK,CAAC,MAAM,IAAI,IAAI,GAAG,MAAM,CAAC,OAAO,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC;YAC5D,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QACzB,CAAC;IACH,CAAC,CAAC;IACF,GAAG,CAAC,IAAI,CAAC,gBAAgB,EAAE,CAAC,EAAE,CAAC,CAAC;IAChC,GAAG,CAAC,IAAI,CAAC,iBAAiB,EAAE,EAAE,CAAC,CAAC;IAChC,KAAK,MAAM,KAAK,IAAI,MAAM,CAAC,MAAM,EAAE,EAAE,CAAC;QACpC,IAAI,KAAK,CAAC,MAAM,KAAK,EAAE,EAAE,CAAC;YACxB,SAAS,CAAC,IAAI,CAAC,EAAE,GAAG,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;QACrC,CAAC;IACH,CAAC;IAED,OAAO,SAAS,CAAC;AACnB,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,84 @@
1
1
  {
2
+ "author": {
3
+ "email": "oleg@ethberry.io",
4
+ "name": "OlegGun",
5
+ "url": "https://ethberry.io/"
6
+ },
7
+ "bugs": {
8
+ "url": "https://github.com/ethberry/nestjs-router-solana/issues"
9
+ },
10
+ "description": "Solana block reader for NestJS: routes transfers to controllers",
11
+ "devDependencies": {
12
+ "cron": "4.4.0",
13
+ "@ethberry/cross-env": "0.0.5",
14
+ "@ethberry/eslint-config": "5.0.13",
15
+ "@jest/globals": "30.5.2",
16
+ "@nestjs/common": "12.5.0",
17
+ "@nestjs/config": "12.1.1",
18
+ "@nestjs/core": "12.5.0",
19
+ "@nestjs/microservices": "12.5.0",
20
+ "@nestjs/schedule": "12.0.4",
21
+ "@nestjs/testing": "12.5.0",
22
+ "@solana-program/system": "0.16.0",
23
+ "@solana-program/token": "0.18.0",
24
+ "@solana/kit": "8.6.0",
25
+ "@types/jest": "30.0.0",
26
+ "@types/node": "24.19.2",
27
+ "husky": "9.1.7",
28
+ "jest": "30.5.2",
29
+ "jest-environment-node": "30.5.2",
30
+ "lint-staged": "17.6.0",
31
+ "prettier": "3.9.10",
32
+ "reflect-metadata": "0.2.2",
33
+ "rimraf": "6.1.4",
34
+ "rxjs": "7.8.2",
35
+ "ts-jest": "29.4.15",
36
+ "typescript": "5.9.3"
37
+ },
38
+ "engines": {
39
+ "node": ">=26"
40
+ },
41
+ "exports": {
42
+ ".": {
43
+ "types": "./dist/index.d.ts",
44
+ "import": "./dist/index.js",
45
+ "default": "./dist/index.js"
46
+ }
47
+ },
48
+ "keywords": [],
49
+ "license": "UNLICENSED",
50
+ "main": "./dist/index.js",
2
51
  "name": "@ethberry/nestjs-router-solana",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
52
+ "type": "module",
53
+ "peerDependencies": {
54
+ "cron": "^4.4.0",
55
+ "@nestjs/common": "^12.5.0",
56
+ "@nestjs/config": "^12.1.1",
57
+ "@nestjs/core": "^12.5.0",
58
+ "@nestjs/microservices": "^12.5.0",
59
+ "@nestjs/schedule": "^12.0.4",
60
+ "@solana/kit": "^8.6.0",
61
+ "rxjs": "^7.8.2"
62
+ },
63
+ "private": false,
64
+ "publishConfig": {
65
+ "access": "public",
66
+ "registry": "https://npm.pkg.github.com/"
67
+ },
68
+ "repository": {
69
+ "type": "git",
70
+ "url": "git+https://github.com/ethberry/nestjs-router-solana.git"
71
+ },
72
+ "scripts": {
73
+ "build": "tsc",
74
+ "lint": "eslint . --fix",
75
+ "prebuild": "rimraf dist/",
76
+ "prepare": "husky",
77
+ "prettier": "prettier . --write",
78
+ "test": "npm run typecheck && cross-env NODE_OPTIONS=--experimental-vm-modules NODE_ENV=${NODE_ENV:=test} jest --detectOpenHandles --runInBand --forceExit",
79
+ "typecheck": "tsc -p tsconfig.test.json"
80
+ },
81
+ "title": "NestJS Solana module",
82
+ "types": "./dist/index.d.ts",
83
+ "version": "1.1.0"
84
+ }