@elisym/sdk 0.14.0 → 0.15.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/dist/index.d.cts CHANGED
@@ -4,6 +4,7 @@ import { A as Asset } from './assets-C-nzSYD4.cjs';
4
4
  export { C as Chain, K as KNOWN_ASSETS, N as NATIVE_SOL, U as USDC_SOLANA_DEVNET, a as assetByKey, b as assetKey, f as formatAssetAmount, p as parseAssetAmount, r as resolveAssetFromPaymentRequest, c as resolveKnownAsset } from './assets-C-nzSYD4.cjs';
5
5
  import { z } from 'zod';
6
6
  export { G as GlobalConfig, a as GlobalConfigSchema, S as SessionSpendLimitEntry, b as SessionSpendLimitEntrySchema } from './global-schema-CddHP2nk.cjs';
7
+ export { R as RateLimitDecision, S as SlidingWindowLimiter, a as SlidingWindowLimiterOptions, c as createSlidingWindowLimiter } from './rateLimiter-CoEmZkSX.cjs';
7
8
 
8
9
  declare class ElisymIdentity {
9
10
  private _secretKey;
@@ -291,6 +292,12 @@ interface BuildTransactionOptions {
291
292
  * attached either way.
292
293
  */
293
294
  jobEventId?: string;
295
+ /**
296
+ * elisym-config program ID. Used to derive the `NetworkStats` PDA targeted
297
+ * by the appended `increment_stats` instruction. Defaults to the devnet
298
+ * deployment when omitted.
299
+ */
300
+ programId?: Address;
294
301
  }
295
302
 
296
303
  declare class NostrPool {
@@ -661,6 +668,7 @@ declare class SolanaPaymentStrategy implements PaymentStrategy {
661
668
  */
662
669
  declare function buildPaymentInstructions(paymentRequest: PaymentRequestData, payerSigner: Signer, options?: {
663
670
  jobEventId?: string;
671
+ programId?: Address;
664
672
  }): Promise<readonly unknown[]>;
665
673
  /**
666
674
  * Convenience wrapper: fetch the on-chain protocol config first, then build a
@@ -970,6 +978,24 @@ interface AggregateNetworkStatsOptions {
970
978
  * up as a positive delta, so it is naturally excluded.
971
979
  */
972
980
  declare function aggregateNetworkStats(rpc: Rpc<SolanaRpcApi>, options?: AggregateNetworkStatsOptions): Promise<NetworkStatsResult>;
981
+ /**
982
+ * Best-effort network stats read from the on-chain `NetworkStats` PDA
983
+ * maintained by the elisym-config program. One `getAccountInfo` call - no
984
+ * signature scans, no per-tx aggregation.
985
+ *
986
+ * The PDA is incremented by the client SDK alongside each payment and is not
987
+ * yet bound to a verified transfer, so totals can be inflated cheaply by a
988
+ * malicious caller. Authoritative tracking will land with the escrow rewrite.
989
+ *
990
+ * Returns `null` when the PDA has not been initialized yet (admin must call
991
+ * `initialize_stats` once after program upgrade).
992
+ */
993
+ interface OnchainNetworkStats {
994
+ jobCount: number;
995
+ volumeNative: bigint;
996
+ volumeUsdc: bigint;
997
+ }
998
+ declare function getNetworkStats(rpc: Rpc<SolanaRpcApi>, programId: Address): Promise<OnchainNetworkStats | null>;
973
999
 
974
1000
  /**
975
1001
  * Snapshot of the on-chain elisym-config program state.
@@ -1032,50 +1058,6 @@ declare class BoundedSet<T> {
1032
1058
  add(item: T): void;
1033
1059
  }
1034
1060
 
1035
- /**
1036
- * Sliding-window rate limiter keyed by an arbitrary string (typically a
1037
- * customer pubkey). Each key gets at most `maxPerWindow` requests inside a
1038
- * rolling `windowMs`. Stale timestamps are pruned lazily on every `check`.
1039
- * When the tracked-key set grows past `maxKeys`, the least-recently-used
1040
- * key is evicted so an attacker cannot exhaust memory by cycling keys.
1041
- *
1042
- * Thread-safety: not required. Designed for single-threaded JS consumers
1043
- * (Node/Bun event loops, browser main thread). No timers - pruning happens
1044
- * inside `check` and `prune`.
1045
- */
1046
- interface SlidingWindowLimiterOptions {
1047
- /** Rolling window width, in ms. */
1048
- windowMs: number;
1049
- /** Max hits allowed per key inside the window. */
1050
- maxPerWindow: number;
1051
- /** Cap on total tracked keys. LRU-evicted past this cap. */
1052
- maxKeys: number;
1053
- }
1054
- interface RateLimitDecision {
1055
- allowed: boolean;
1056
- /** Wall-clock timestamp (ms) when the limit window will reset for this key. */
1057
- resetAt: number;
1058
- /** Number of hits inside the current window after this call (or the attempted hit if denied). */
1059
- count: number;
1060
- }
1061
- interface SlidingWindowLimiter {
1062
- /** Record a hit against `key`; return whether it was allowed. */
1063
- check(key: string, now?: number): RateLimitDecision;
1064
- /**
1065
- * Inspect the current state for `key` without recording a hit. Useful
1066
- * when a single request must clear multiple limiters and callers want
1067
- * to avoid double-counting against one limiter after another denies.
1068
- */
1069
- peek(key: string, now?: number): RateLimitDecision;
1070
- /** Drop entries whose windows have fully elapsed. Bounded memory hygiene. */
1071
- prune(now?: number): void;
1072
- /** Current number of tracked keys. */
1073
- size(): number;
1074
- /** Clear all state. */
1075
- reset(): void;
1076
- }
1077
- declare function createSlidingWindowLimiter(options: SlidingWindowLimiterOptions): SlidingWindowLimiter;
1078
-
1079
1061
  /**
1080
1062
  * Canonical pino redact paths for the elisym stack. Plugin, CLI, MCP, and
1081
1063
  * any downstream integrator should consume these arrays directly - one
@@ -1180,4 +1162,4 @@ declare const LIMITS: {
1180
1162
  readonly MAX_CAPABILITY_LENGTH: 64;
1181
1163
  };
1182
1164
 
1183
- export { type Agent, type AggregateNetworkStatsOptions, Asset, BoundedSet, type BuildTransactionOptions, type CapabilityCard, DEFAULTS, DEFAULT_KIND_OFFSET, DEFAULT_REDACT_PATHS, DiscoveryService, ELISYM_PROTOCOL_TAG, ElisymClient, type ElisymClientConfig, type ElisymClientFullConfig, ElisymIdentity, type EstimatePriorityFeeOptions, type EstimateSolFeeOptions, type GetProtocolConfigOptions, INPUT_REDACT_PATHS, type Job, type JobStatus, type JobSubscriptionOptions, type JobUpdateCallbacks, KIND_APP_HANDLER, KIND_JOB_FEEDBACK, KIND_JOB_REQUEST, KIND_JOB_REQUEST_BASE, KIND_JOB_RESULT, KIND_JOB_RESULT_BASE, KIND_PING, KIND_PONG, LAMPORTS_PER_SOL, LIMITS, MarketplaceService, MediaService, type Network, type NetworkBaselineEstimate, type NetworkBaselineOptions, type NetworkStats, type NetworkStatsResult, NostrPool, PROTOCOL_PROGRAM_ID_DEVNET, type ParseOptions, type ParseResult, type ParsedPaymentRequest, type PaymentAssetRef, type PaymentInfo, type PaymentRequestData, PaymentRequestSchema, type PaymentStrategy, type PaymentValidationCode, type PaymentValidationError, type PingResult, PingService, type ProtocolCluster, type ProtocolConfig, type ProtocolConfigInput, type QuickVerifyReason, type QuickVerifyResult, RELAYS, type RankKey, type RateLimitDecision, SECRET_REDACT_PATHS, type Signer, type SlidingWindowLimiter, type SlidingWindowLimiterOptions, type SolFeeEstimate, SolanaPaymentStrategy, type SubCloser, type SubmitJobOptions, type VerifyOptions, type VerifyResult, aggregateNetworkStats, assertExpiry, assertLamports, buildPaymentInstructions, calculateProtocolFee, clearPriorityFeeCache, clearProtocolConfigCache, clearQuickVerifyCache, compareAgentsByRank, computeRankKey, createPaymentRequestWithOnchainConfig, createSlidingWindowLimiter, estimateNetworkBaseline, estimatePriorityFeeMicroLamports, estimateSolFeeLamports, formatFeeBreakdown, formatNetworkBaseline, formatSol, getProtocolConfig, getProtocolProgramId, jobRequestKind, jobResultKind, makeCensor, nip44Decrypt, nip44Encrypt, parsePaymentRequest, pickPercentileFee, timeAgo, toDTag, truncateKey, validateAgentName, validateExpiry, verifyJobPaymentQuick };
1165
+ export { type Agent, type AggregateNetworkStatsOptions, Asset, BoundedSet, type BuildTransactionOptions, type CapabilityCard, DEFAULTS, DEFAULT_KIND_OFFSET, DEFAULT_REDACT_PATHS, DiscoveryService, ELISYM_PROTOCOL_TAG, ElisymClient, type ElisymClientConfig, type ElisymClientFullConfig, ElisymIdentity, type EstimatePriorityFeeOptions, type EstimateSolFeeOptions, type GetProtocolConfigOptions, INPUT_REDACT_PATHS, type Job, type JobStatus, type JobSubscriptionOptions, type JobUpdateCallbacks, KIND_APP_HANDLER, KIND_JOB_FEEDBACK, KIND_JOB_REQUEST, KIND_JOB_REQUEST_BASE, KIND_JOB_RESULT, KIND_JOB_RESULT_BASE, KIND_PING, KIND_PONG, LAMPORTS_PER_SOL, LIMITS, MarketplaceService, MediaService, type Network, type NetworkBaselineEstimate, type NetworkBaselineOptions, type NetworkStats, type NetworkStatsResult, NostrPool, type OnchainNetworkStats, PROTOCOL_PROGRAM_ID_DEVNET, type ParseOptions, type ParseResult, type ParsedPaymentRequest, type PaymentAssetRef, type PaymentInfo, type PaymentRequestData, PaymentRequestSchema, type PaymentStrategy, type PaymentValidationCode, type PaymentValidationError, type PingResult, PingService, type ProtocolCluster, type ProtocolConfig, type ProtocolConfigInput, type QuickVerifyReason, type QuickVerifyResult, RELAYS, type RankKey, SECRET_REDACT_PATHS, type Signer, type SolFeeEstimate, SolanaPaymentStrategy, type SubCloser, type SubmitJobOptions, type VerifyOptions, type VerifyResult, aggregateNetworkStats, assertExpiry, assertLamports, buildPaymentInstructions, calculateProtocolFee, clearPriorityFeeCache, clearProtocolConfigCache, clearQuickVerifyCache, compareAgentsByRank, computeRankKey, createPaymentRequestWithOnchainConfig, estimateNetworkBaseline, estimatePriorityFeeMicroLamports, estimateSolFeeLamports, formatFeeBreakdown, formatNetworkBaseline, formatSol, getNetworkStats, getProtocolConfig, getProtocolProgramId, jobRequestKind, jobResultKind, makeCensor, nip44Decrypt, nip44Encrypt, parsePaymentRequest, pickPercentileFee, timeAgo, toDTag, truncateKey, validateAgentName, validateExpiry, verifyJobPaymentQuick };
package/dist/index.d.ts CHANGED
@@ -4,6 +4,7 @@ import { A as Asset } from './assets-C-nzSYD4.js';
4
4
  export { C as Chain, K as KNOWN_ASSETS, N as NATIVE_SOL, U as USDC_SOLANA_DEVNET, a as assetByKey, b as assetKey, f as formatAssetAmount, p as parseAssetAmount, r as resolveAssetFromPaymentRequest, c as resolveKnownAsset } from './assets-C-nzSYD4.js';
5
5
  import { z } from 'zod';
6
6
  export { G as GlobalConfig, a as GlobalConfigSchema, S as SessionSpendLimitEntry, b as SessionSpendLimitEntrySchema } from './global-schema-CddHP2nk.js';
7
+ export { R as RateLimitDecision, S as SlidingWindowLimiter, a as SlidingWindowLimiterOptions, c as createSlidingWindowLimiter } from './rateLimiter-CoEmZkSX.js';
7
8
 
8
9
  declare class ElisymIdentity {
9
10
  private _secretKey;
@@ -291,6 +292,12 @@ interface BuildTransactionOptions {
291
292
  * attached either way.
292
293
  */
293
294
  jobEventId?: string;
295
+ /**
296
+ * elisym-config program ID. Used to derive the `NetworkStats` PDA targeted
297
+ * by the appended `increment_stats` instruction. Defaults to the devnet
298
+ * deployment when omitted.
299
+ */
300
+ programId?: Address;
294
301
  }
295
302
 
296
303
  declare class NostrPool {
@@ -661,6 +668,7 @@ declare class SolanaPaymentStrategy implements PaymentStrategy {
661
668
  */
662
669
  declare function buildPaymentInstructions(paymentRequest: PaymentRequestData, payerSigner: Signer, options?: {
663
670
  jobEventId?: string;
671
+ programId?: Address;
664
672
  }): Promise<readonly unknown[]>;
665
673
  /**
666
674
  * Convenience wrapper: fetch the on-chain protocol config first, then build a
@@ -970,6 +978,24 @@ interface AggregateNetworkStatsOptions {
970
978
  * up as a positive delta, so it is naturally excluded.
971
979
  */
972
980
  declare function aggregateNetworkStats(rpc: Rpc<SolanaRpcApi>, options?: AggregateNetworkStatsOptions): Promise<NetworkStatsResult>;
981
+ /**
982
+ * Best-effort network stats read from the on-chain `NetworkStats` PDA
983
+ * maintained by the elisym-config program. One `getAccountInfo` call - no
984
+ * signature scans, no per-tx aggregation.
985
+ *
986
+ * The PDA is incremented by the client SDK alongside each payment and is not
987
+ * yet bound to a verified transfer, so totals can be inflated cheaply by a
988
+ * malicious caller. Authoritative tracking will land with the escrow rewrite.
989
+ *
990
+ * Returns `null` when the PDA has not been initialized yet (admin must call
991
+ * `initialize_stats` once after program upgrade).
992
+ */
993
+ interface OnchainNetworkStats {
994
+ jobCount: number;
995
+ volumeNative: bigint;
996
+ volumeUsdc: bigint;
997
+ }
998
+ declare function getNetworkStats(rpc: Rpc<SolanaRpcApi>, programId: Address): Promise<OnchainNetworkStats | null>;
973
999
 
974
1000
  /**
975
1001
  * Snapshot of the on-chain elisym-config program state.
@@ -1032,50 +1058,6 @@ declare class BoundedSet<T> {
1032
1058
  add(item: T): void;
1033
1059
  }
1034
1060
 
1035
- /**
1036
- * Sliding-window rate limiter keyed by an arbitrary string (typically a
1037
- * customer pubkey). Each key gets at most `maxPerWindow` requests inside a
1038
- * rolling `windowMs`. Stale timestamps are pruned lazily on every `check`.
1039
- * When the tracked-key set grows past `maxKeys`, the least-recently-used
1040
- * key is evicted so an attacker cannot exhaust memory by cycling keys.
1041
- *
1042
- * Thread-safety: not required. Designed for single-threaded JS consumers
1043
- * (Node/Bun event loops, browser main thread). No timers - pruning happens
1044
- * inside `check` and `prune`.
1045
- */
1046
- interface SlidingWindowLimiterOptions {
1047
- /** Rolling window width, in ms. */
1048
- windowMs: number;
1049
- /** Max hits allowed per key inside the window. */
1050
- maxPerWindow: number;
1051
- /** Cap on total tracked keys. LRU-evicted past this cap. */
1052
- maxKeys: number;
1053
- }
1054
- interface RateLimitDecision {
1055
- allowed: boolean;
1056
- /** Wall-clock timestamp (ms) when the limit window will reset for this key. */
1057
- resetAt: number;
1058
- /** Number of hits inside the current window after this call (or the attempted hit if denied). */
1059
- count: number;
1060
- }
1061
- interface SlidingWindowLimiter {
1062
- /** Record a hit against `key`; return whether it was allowed. */
1063
- check(key: string, now?: number): RateLimitDecision;
1064
- /**
1065
- * Inspect the current state for `key` without recording a hit. Useful
1066
- * when a single request must clear multiple limiters and callers want
1067
- * to avoid double-counting against one limiter after another denies.
1068
- */
1069
- peek(key: string, now?: number): RateLimitDecision;
1070
- /** Drop entries whose windows have fully elapsed. Bounded memory hygiene. */
1071
- prune(now?: number): void;
1072
- /** Current number of tracked keys. */
1073
- size(): number;
1074
- /** Clear all state. */
1075
- reset(): void;
1076
- }
1077
- declare function createSlidingWindowLimiter(options: SlidingWindowLimiterOptions): SlidingWindowLimiter;
1078
-
1079
1061
  /**
1080
1062
  * Canonical pino redact paths for the elisym stack. Plugin, CLI, MCP, and
1081
1063
  * any downstream integrator should consume these arrays directly - one
@@ -1180,4 +1162,4 @@ declare const LIMITS: {
1180
1162
  readonly MAX_CAPABILITY_LENGTH: 64;
1181
1163
  };
1182
1164
 
1183
- export { type Agent, type AggregateNetworkStatsOptions, Asset, BoundedSet, type BuildTransactionOptions, type CapabilityCard, DEFAULTS, DEFAULT_KIND_OFFSET, DEFAULT_REDACT_PATHS, DiscoveryService, ELISYM_PROTOCOL_TAG, ElisymClient, type ElisymClientConfig, type ElisymClientFullConfig, ElisymIdentity, type EstimatePriorityFeeOptions, type EstimateSolFeeOptions, type GetProtocolConfigOptions, INPUT_REDACT_PATHS, type Job, type JobStatus, type JobSubscriptionOptions, type JobUpdateCallbacks, KIND_APP_HANDLER, KIND_JOB_FEEDBACK, KIND_JOB_REQUEST, KIND_JOB_REQUEST_BASE, KIND_JOB_RESULT, KIND_JOB_RESULT_BASE, KIND_PING, KIND_PONG, LAMPORTS_PER_SOL, LIMITS, MarketplaceService, MediaService, type Network, type NetworkBaselineEstimate, type NetworkBaselineOptions, type NetworkStats, type NetworkStatsResult, NostrPool, PROTOCOL_PROGRAM_ID_DEVNET, type ParseOptions, type ParseResult, type ParsedPaymentRequest, type PaymentAssetRef, type PaymentInfo, type PaymentRequestData, PaymentRequestSchema, type PaymentStrategy, type PaymentValidationCode, type PaymentValidationError, type PingResult, PingService, type ProtocolCluster, type ProtocolConfig, type ProtocolConfigInput, type QuickVerifyReason, type QuickVerifyResult, RELAYS, type RankKey, type RateLimitDecision, SECRET_REDACT_PATHS, type Signer, type SlidingWindowLimiter, type SlidingWindowLimiterOptions, type SolFeeEstimate, SolanaPaymentStrategy, type SubCloser, type SubmitJobOptions, type VerifyOptions, type VerifyResult, aggregateNetworkStats, assertExpiry, assertLamports, buildPaymentInstructions, calculateProtocolFee, clearPriorityFeeCache, clearProtocolConfigCache, clearQuickVerifyCache, compareAgentsByRank, computeRankKey, createPaymentRequestWithOnchainConfig, createSlidingWindowLimiter, estimateNetworkBaseline, estimatePriorityFeeMicroLamports, estimateSolFeeLamports, formatFeeBreakdown, formatNetworkBaseline, formatSol, getProtocolConfig, getProtocolProgramId, jobRequestKind, jobResultKind, makeCensor, nip44Decrypt, nip44Encrypt, parsePaymentRequest, pickPercentileFee, timeAgo, toDTag, truncateKey, validateAgentName, validateExpiry, verifyJobPaymentQuick };
1165
+ export { type Agent, type AggregateNetworkStatsOptions, Asset, BoundedSet, type BuildTransactionOptions, type CapabilityCard, DEFAULTS, DEFAULT_KIND_OFFSET, DEFAULT_REDACT_PATHS, DiscoveryService, ELISYM_PROTOCOL_TAG, ElisymClient, type ElisymClientConfig, type ElisymClientFullConfig, ElisymIdentity, type EstimatePriorityFeeOptions, type EstimateSolFeeOptions, type GetProtocolConfigOptions, INPUT_REDACT_PATHS, type Job, type JobStatus, type JobSubscriptionOptions, type JobUpdateCallbacks, KIND_APP_HANDLER, KIND_JOB_FEEDBACK, KIND_JOB_REQUEST, KIND_JOB_REQUEST_BASE, KIND_JOB_RESULT, KIND_JOB_RESULT_BASE, KIND_PING, KIND_PONG, LAMPORTS_PER_SOL, LIMITS, MarketplaceService, MediaService, type Network, type NetworkBaselineEstimate, type NetworkBaselineOptions, type NetworkStats, type NetworkStatsResult, NostrPool, type OnchainNetworkStats, PROTOCOL_PROGRAM_ID_DEVNET, type ParseOptions, type ParseResult, type ParsedPaymentRequest, type PaymentAssetRef, type PaymentInfo, type PaymentRequestData, PaymentRequestSchema, type PaymentStrategy, type PaymentValidationCode, type PaymentValidationError, type PingResult, PingService, type ProtocolCluster, type ProtocolConfig, type ProtocolConfigInput, type QuickVerifyReason, type QuickVerifyResult, RELAYS, type RankKey, SECRET_REDACT_PATHS, type Signer, type SolFeeEstimate, SolanaPaymentStrategy, type SubCloser, type SubmitJobOptions, type VerifyOptions, type VerifyResult, aggregateNetworkStats, assertExpiry, assertLamports, buildPaymentInstructions, calculateProtocolFee, clearPriorityFeeCache, clearProtocolConfigCache, clearQuickVerifyCache, compareAgentsByRank, computeRankKey, createPaymentRequestWithOnchainConfig, estimateNetworkBaseline, estimatePriorityFeeMicroLamports, estimateSolFeeLamports, formatFeeBreakdown, formatNetworkBaseline, formatSol, getNetworkStats, getProtocolConfig, getProtocolProgramId, jobRequestKind, jobResultKind, makeCensor, nip44Decrypt, nip44Encrypt, parsePaymentRequest, pickPercentileFee, timeAgo, toDTag, truncateKey, validateAgentName, validateExpiry, verifyJobPaymentQuick };
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
+ import { pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, setTransactionMessageComputeUnitLimit, setTransactionMessageComputeUnitPrice, appendTransactionMessageInstructions, signTransactionMessageWithSigners, address, AccountRole, isAddress, getProgramDerivedAddress, assertAccountExists, getAddressDecoder, fetchEncodedAccount, transformEncoder, getStructEncoder, fixEncoderSize, getBytesEncoder, getU64Encoder, getBooleanEncoder, decodeAccount, upgradeRoleToSigner, getStructDecoder, fixDecoderSize, getBytesDecoder, getU8Decoder, getU64Decoder, getU128Decoder, getI64Decoder, getOptionDecoder, getU16Decoder, getBooleanDecoder, isTransactionSigner as isTransactionSigner$1 } from '@solana/kit';
1
2
  import { getAddMemoInstruction } from '@solana-program/memo';
2
3
  import { getTransferSolInstruction } from '@solana-program/system';
3
4
  import { findAssociatedTokenPda, TOKEN_PROGRAM_ADDRESS, getCreateAssociatedTokenIdempotentInstruction, ASSOCIATED_TOKEN_PROGRAM_ADDRESS, getTransferCheckedInstruction } from '@solana-program/token';
4
- import { pipe, createTransactionMessage, setTransactionMessageFeePayerSigner, setTransactionMessageLifetimeUsingBlockhash, setTransactionMessageComputeUnitLimit, setTransactionMessageComputeUnitPrice, appendTransactionMessageInstructions, signTransactionMessageWithSigners, address, AccountRole, isAddress, getProgramDerivedAddress, assertAccountExists, getAddressDecoder, fetchEncodedAccount, decodeAccount, getStructDecoder, fixDecoderSize, getBytesDecoder, getU8Decoder, getOptionDecoder, getU16Decoder, getBooleanDecoder, getI64Decoder } from '@solana/kit';
5
5
  import Decimal3 from 'decimal.js-light';
6
6
  import { z } from 'zod';
7
7
  import { verifyEvent, finalizeEvent, getPublicKey, nip19, generateSecretKey, SimplePool } from 'nostr-tools';
@@ -103,8 +103,107 @@ async function fetchMaybeConfig(rpc, address4, config) {
103
103
  const maybeAccount = await fetchEncodedAccount(rpc, address4, config);
104
104
  return decodeConfig(maybeAccount);
105
105
  }
106
+ function getNetworkStatsDecoder() {
107
+ return getStructDecoder([
108
+ ["discriminator", fixDecoderSize(getBytesDecoder(), 8)],
109
+ ["version", getU8Decoder()],
110
+ ["bump", getU8Decoder()],
111
+ ["jobCount", getU64Decoder()],
112
+ ["volumeNative", getU128Decoder()],
113
+ ["volumeUsdc", getU128Decoder()],
114
+ ["lastUpdated", getI64Decoder()],
115
+ ["reserved", fixDecoderSize(getBytesDecoder(), 128)]
116
+ ]);
117
+ }
118
+ function decodeNetworkStats(encodedAccount) {
119
+ return decodeAccount(
120
+ encodedAccount,
121
+ getNetworkStatsDecoder()
122
+ );
123
+ }
124
+ async function fetchMaybeNetworkStats(rpc, address4, config) {
125
+ const maybeAccount = await fetchEncodedAccount(rpc, address4, config);
126
+ return decodeNetworkStats(maybeAccount);
127
+ }
128
+ var ELISYM_CONFIG_PROGRAM_ADDRESS = "BrX1CRkSgvcjxBvc2bgc3QqgWjinusofDmeP7ZVxvwrE";
106
129
  if (process.env.NODE_ENV !== "production") ;
130
+ function expectAddress(value) {
131
+ if (!value) {
132
+ throw new Error("Expected a Address.");
133
+ }
134
+ if (typeof value === "object" && "address" in value) {
135
+ return value.address;
136
+ }
137
+ if (Array.isArray(value)) {
138
+ return value[0];
139
+ }
140
+ return value;
141
+ }
142
+ function getAccountMetaFactory(programAddress, optionalAccountStrategy) {
143
+ return (account) => {
144
+ if (!account.value) {
145
+ return Object.freeze({
146
+ address: programAddress,
147
+ role: AccountRole.READONLY
148
+ });
149
+ }
150
+ const writableRole = account.isWritable ? AccountRole.WRITABLE : AccountRole.READONLY;
151
+ return Object.freeze({
152
+ address: expectAddress(account.value),
153
+ role: isTransactionSigner(account.value) ? upgradeRoleToSigner(writableRole) : writableRole,
154
+ ...isTransactionSigner(account.value) ? { signer: account.value } : {}
155
+ });
156
+ };
157
+ }
158
+ function isTransactionSigner(value) {
159
+ return !!value && typeof value === "object" && "address" in value && isTransactionSigner$1(value);
160
+ }
161
+ var INCREMENT_STATS_DISCRIMINATOR = new Uint8Array([
162
+ 145,
163
+ 78,
164
+ 96,
165
+ 206,
166
+ 45,
167
+ 21,
168
+ 111,
169
+ 175
170
+ ]);
171
+ function getIncrementStatsInstructionDataEncoder() {
172
+ return transformEncoder(
173
+ getStructEncoder([
174
+ ["discriminator", fixEncoderSize(getBytesEncoder(), 8)],
175
+ ["amount", getU64Encoder()],
176
+ ["isNative", getBooleanEncoder()]
177
+ ]),
178
+ (value) => ({ ...value, discriminator: INCREMENT_STATS_DISCRIMINATOR })
179
+ );
180
+ }
181
+ function getIncrementStatsInstruction(input, config) {
182
+ const programAddress = config?.programAddress ?? ELISYM_CONFIG_PROGRAM_ADDRESS;
183
+ const originalAccounts = {
184
+ stats: { value: input.stats ?? null, isWritable: true },
185
+ eventAuthority: { value: input.eventAuthority ?? null, isWritable: false },
186
+ program: { value: input.program ?? null, isWritable: false }
187
+ };
188
+ const accounts = originalAccounts;
189
+ const args = { ...input };
190
+ const getAccountMeta = getAccountMetaFactory(programAddress);
191
+ const instruction = {
192
+ accounts: [
193
+ getAccountMeta(accounts.stats),
194
+ getAccountMeta(accounts.eventAuthority),
195
+ getAccountMeta(accounts.program)
196
+ ],
197
+ programAddress,
198
+ data: getIncrementStatsInstructionDataEncoder().encode(
199
+ args
200
+ )
201
+ };
202
+ return instruction;
203
+ }
107
204
  var CONFIG_SEED = "config";
205
+ var STATS_SEED = "network_stats";
206
+ var EVENT_AUTHORITY_SEED = "__event_authority";
108
207
  async function deriveConfigAddress(programId) {
109
208
  const [pda] = await getProgramDerivedAddress({
110
209
  programAddress: programId,
@@ -112,6 +211,20 @@ async function deriveConfigAddress(programId) {
112
211
  });
113
212
  return pda;
114
213
  }
214
+ async function deriveNetworkStatsAddress(programId) {
215
+ const [pda] = await getProgramDerivedAddress({
216
+ programAddress: programId,
217
+ seeds: [new TextEncoder().encode(STATS_SEED)]
218
+ });
219
+ return pda;
220
+ }
221
+ async function deriveEventAuthorityAddress(programId) {
222
+ const [pda] = await getProgramDerivedAddress({
223
+ programAddress: programId,
224
+ seeds: [new TextEncoder().encode(EVENT_AUTHORITY_SEED)]
225
+ });
226
+ return pda;
227
+ }
115
228
 
116
229
  // src/config/onchain.ts
117
230
  var CACHE_TTL_MS = 6e4;
@@ -573,7 +686,8 @@ var SolanaPaymentStrategy = class {
573
686
  throw new Error(`Invalid computeUnitLimit: ${computeUnitLimit}. Must be a positive integer.`);
574
687
  }
575
688
  const paymentInstructions = await buildPaymentInstructions(paymentRequest, payerSigner, {
576
- jobEventId: options?.jobEventId
689
+ jobEventId: options?.jobEventId,
690
+ programId: options?.programId
577
691
  });
578
692
  const priorityFeeMicroLamports = options?.priorityFeeMicroLamports ?? await estimatePriorityFeeMicroLamports(rpc, {
579
693
  percentile: options?.priorityFeePercentile ?? DEFAULT_PRIORITY_FEE_PERCENTILE
@@ -875,8 +989,21 @@ async function buildPaymentInstructions(paymentRequest, payerSigner, options) {
875
989
  const recipient = address(paymentRequest.recipient);
876
990
  const reference = address(paymentRequest.reference);
877
991
  const protocolTag = address(ELISYM_PROTOCOL_TAG);
992
+ const programId = options?.programId ?? getProtocolProgramId("devnet");
878
993
  const feeAmount = paymentRequest.fee_amount ?? 0;
879
994
  const providerAmount = paymentRequest.fee_address && feeAmount > 0 ? paymentRequest.amount - feeAmount : paymentRequest.amount;
995
+ const statsPda = await deriveNetworkStatsAddress(programId);
996
+ const eventAuthority = await deriveEventAuthorityAddress(programId);
997
+ const incrementStatsIx = getIncrementStatsInstruction(
998
+ {
999
+ stats: statsPda,
1000
+ eventAuthority,
1001
+ program: programId,
1002
+ amount: BigInt(paymentRequest.amount),
1003
+ isNative: !resolveAssetFromPaymentRequest(paymentRequest).mint
1004
+ },
1005
+ { programAddress: programId }
1006
+ );
880
1007
  if (providerAmount <= 0) {
881
1008
  throw new Error(
882
1009
  `Fee amount (${feeAmount}) exceeds or equals total amount (${paymentRequest.amount}). Cannot create transaction with non-positive provider amount.`
@@ -912,6 +1039,7 @@ async function buildPaymentInstructions(paymentRequest, payerSigner, options) {
912
1039
  })
913
1040
  );
914
1041
  }
1042
+ instructions2.push(incrementStatsIx);
915
1043
  return instructions2;
916
1044
  }
917
1045
  const mint = address(asset.mint);
@@ -990,6 +1118,7 @@ async function buildPaymentInstructions(paymentRequest, payerSigner, options) {
990
1118
  })
991
1119
  );
992
1120
  }
1121
+ instructions.push(incrementStatsIx);
993
1122
  return instructions;
994
1123
  }
995
1124
  async function createPaymentRequestWithOnchainConfig(rpc, programId, recipient, amount, options) {
@@ -3193,6 +3322,18 @@ function accumulateNativeDeltas(pre, post, volumeByAsset) {
3193
3322
  }
3194
3323
  }
3195
3324
  }
3325
+ async function getNetworkStats(rpc, programId) {
3326
+ const statsPda = await deriveNetworkStatsAddress(programId);
3327
+ const account = await fetchMaybeNetworkStats(rpc, statsPda);
3328
+ if (!account.exists) {
3329
+ return null;
3330
+ }
3331
+ return {
3332
+ jobCount: Number(account.data.jobCount),
3333
+ volumeNative: account.data.volumeNative,
3334
+ volumeUsdc: account.data.volumeUsdc
3335
+ };
3336
+ }
3196
3337
  var SessionSpendLimitEntrySchema = z.object({
3197
3338
  chain: z.enum(["solana"]),
3198
3339
  token: z.string().min(1).max(16).regex(/^[a-z0-9]+$/, "token must be lowercase alphanumeric"),
@@ -3397,6 +3538,6 @@ function makeCensor() {
3397
3538
  };
3398
3539
  }
3399
3540
 
3400
- export { BoundedSet, DEFAULTS, DEFAULT_KIND_OFFSET, DEFAULT_REDACT_PATHS, DiscoveryService, ELISYM_PROTOCOL_TAG, ElisymClient, ElisymIdentity, GlobalConfigSchema, INPUT_REDACT_PATHS, KIND_APP_HANDLER, KIND_JOB_FEEDBACK, KIND_JOB_REQUEST, KIND_JOB_REQUEST_BASE, KIND_JOB_RESULT, KIND_JOB_RESULT_BASE, KIND_PING, KIND_PONG, KNOWN_ASSETS, LAMPORTS_PER_SOL, LIMITS, MarketplaceService, MediaService, NATIVE_SOL, NostrPool, PROTOCOL_PROGRAM_ID_DEVNET, PaymentRequestSchema, PingService, RELAYS, SECRET_REDACT_PATHS, SessionSpendLimitEntrySchema, SolanaPaymentStrategy, USDC_SOLANA_DEVNET, aggregateNetworkStats, assertExpiry, assertLamports, assetByKey, assetKey, buildPaymentInstructions, calculateProtocolFee, clearPriorityFeeCache, clearProtocolConfigCache, clearQuickVerifyCache, compareAgentsByRank, computeRankKey, createPaymentRequestWithOnchainConfig, createSlidingWindowLimiter, estimateNetworkBaseline, estimatePriorityFeeMicroLamports, estimateSolFeeLamports, formatAssetAmount, formatFeeBreakdown, formatNetworkBaseline, formatSol, getProtocolConfig, getProtocolProgramId, jobRequestKind, jobResultKind, makeCensor, nip44Decrypt, nip44Encrypt, parseAssetAmount, parsePaymentRequest, pickPercentileFee, resolveAssetFromPaymentRequest, resolveKnownAsset, timeAgo, toDTag, truncateKey, validateAgentName, validateExpiry, verifyJobPaymentQuick };
3541
+ export { BoundedSet, DEFAULTS, DEFAULT_KIND_OFFSET, DEFAULT_REDACT_PATHS, DiscoveryService, ELISYM_PROTOCOL_TAG, ElisymClient, ElisymIdentity, GlobalConfigSchema, INPUT_REDACT_PATHS, KIND_APP_HANDLER, KIND_JOB_FEEDBACK, KIND_JOB_REQUEST, KIND_JOB_REQUEST_BASE, KIND_JOB_RESULT, KIND_JOB_RESULT_BASE, KIND_PING, KIND_PONG, KNOWN_ASSETS, LAMPORTS_PER_SOL, LIMITS, MarketplaceService, MediaService, NATIVE_SOL, NostrPool, PROTOCOL_PROGRAM_ID_DEVNET, PaymentRequestSchema, PingService, RELAYS, SECRET_REDACT_PATHS, SessionSpendLimitEntrySchema, SolanaPaymentStrategy, USDC_SOLANA_DEVNET, aggregateNetworkStats, assertExpiry, assertLamports, assetByKey, assetKey, buildPaymentInstructions, calculateProtocolFee, clearPriorityFeeCache, clearProtocolConfigCache, clearQuickVerifyCache, compareAgentsByRank, computeRankKey, createPaymentRequestWithOnchainConfig, createSlidingWindowLimiter, estimateNetworkBaseline, estimatePriorityFeeMicroLamports, estimateSolFeeLamports, formatAssetAmount, formatFeeBreakdown, formatNetworkBaseline, formatSol, getNetworkStats, getProtocolConfig, getProtocolProgramId, jobRequestKind, jobResultKind, makeCensor, nip44Decrypt, nip44Encrypt, parseAssetAmount, parsePaymentRequest, pickPercentileFee, resolveAssetFromPaymentRequest, resolveKnownAsset, timeAgo, toDTag, truncateKey, validateAgentName, validateExpiry, verifyJobPaymentQuick };
3401
3542
  //# sourceMappingURL=index.js.map
3402
3543
  //# sourceMappingURL=index.js.map