openttt 0.2.7 → 0.2.9

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.ts CHANGED
@@ -1,12 +1,10 @@
1
1
  export * from "./evm_connector";
2
2
  export * from "./x402_enforcer";
3
- export * from "./ttt_builder";
4
3
  export * from "./protocol_fee";
5
4
  export * from "./pool_registry";
6
5
  export * from "./v4_hook";
7
6
  export * from "./logger";
8
7
  export * from "./types";
9
- export * from "./ttt_client";
10
8
  export * from "./http_client";
11
9
  export * from "./time_synthesis";
12
10
  export * from "./dynamic_fee";
package/dist/index.js CHANGED
@@ -21,13 +21,13 @@ Object.defineProperty(exports, "__esModule", { value: true });
21
21
  // 위 모듈은 서버 코드에서 직접 경로로 import할 것.
22
22
  __exportStar(require("./evm_connector"), exports);
23
23
  __exportStar(require("./x402_enforcer"), exports);
24
- __exportStar(require("./ttt_builder"), exports);
24
+ // ttt_builder omitted — requires adaptive_switch (server-internal, not in public SDK)
25
25
  __exportStar(require("./protocol_fee"), exports);
26
26
  __exportStar(require("./pool_registry"), exports);
27
27
  __exportStar(require("./v4_hook"), exports);
28
28
  __exportStar(require("./logger"), exports);
29
29
  __exportStar(require("./types"), exports);
30
- __exportStar(require("./ttt_client"), exports);
30
+ // ttt_client omitted — requires auto_mint (server-internal, not in public SDK)
31
31
  __exportStar(require("./http_client"), exports);
32
32
  __exportStar(require("./time_synthesis"), exports);
33
33
  __exportStar(require("./dynamic_fee"), exports);
@@ -14,8 +14,10 @@ export interface IntegrityVerifyResult {
14
14
  export declare class IntegrityClient {
15
15
  private baseUrl;
16
16
  private timeoutMs;
17
+ private apiKey;
17
18
  constructor(baseUrl?: string, options?: {
18
19
  timeoutMs?: number;
20
+ apiKey?: string;
19
21
  });
20
22
  /**
21
23
  * Forward pass: encode data through integrity pipeline (server-side).
@@ -12,9 +12,11 @@ exports.setDefaultIntegrityClient = setDefaultIntegrityClient;
12
12
  class IntegrityClient {
13
13
  baseUrl;
14
14
  timeoutMs;
15
+ apiKey;
15
16
  constructor(baseUrl = "https://integrity.helmprotocol.com/api/v1", options) {
16
17
  this.baseUrl = baseUrl.replace(/\/$/, "");
17
18
  this.timeoutMs = options?.timeoutMs ?? 5000;
19
+ this.apiKey = options?.apiKey ?? (typeof process !== "undefined" ? process.env["INTEGRITY_API_KEY"] : undefined);
18
20
  }
19
21
  /**
20
22
  * Forward pass: encode data through integrity pipeline (server-side).
@@ -27,7 +29,10 @@ class IntegrityClient {
27
29
  try {
28
30
  const resp = await fetch(`${this.baseUrl}/encode`, {
29
31
  method: "POST",
30
- headers: { "Content-Type": "application/json" },
32
+ headers: {
33
+ "Content-Type": "application/json",
34
+ ...(this.apiKey ? { "X-Integrity-Key": this.apiKey } : {}),
35
+ },
31
36
  body: JSON.stringify({
32
37
  data: Buffer.from(data).toString("hex"),
33
38
  chainId: chainId,
@@ -56,7 +61,10 @@ class IntegrityClient {
56
61
  try {
57
62
  const resp = await fetch(`${this.baseUrl}/verify`, {
58
63
  method: "POST",
59
- headers: { "Content-Type": "application/json" },
64
+ headers: {
65
+ "Content-Type": "application/json",
66
+ ...(this.apiKey ? { "X-Integrity-Key": this.apiKey } : {}),
67
+ },
60
68
  body: JSON.stringify({
61
69
  data: Buffer.from(data).toString("hex"),
62
70
  shards: originalShards.map((s) => Buffer.from(s).toString("hex")),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "openttt",
3
- "version": "0.2.7",
3
+ "version": "0.2.9",
4
4
  "description": "OpenTTT — TLS-grade transaction ordering for DeFi. Time + Logic + Sync.",
5
5
  "license": "BSL-1.1",
6
6
  "repository": {
@@ -30,7 +30,50 @@
30
30
  }
31
31
  },
32
32
  "files": [
33
- "dist",
33
+ "dist/ct_log.js",
34
+ "dist/ct_log.d.ts",
35
+ "dist/dynamic_fee.js",
36
+ "dist/dynamic_fee.d.ts",
37
+ "dist/errors.js",
38
+ "dist/errors.d.ts",
39
+ "dist/evm_connector.js",
40
+ "dist/evm_connector.d.ts",
41
+ "dist/http_client.js",
42
+ "dist/http_client.d.ts",
43
+ "dist/index.js",
44
+ "dist/index.d.ts",
45
+ "dist/integrity_client.js",
46
+ "dist/integrity_client.d.ts",
47
+ "dist/logger.js",
48
+ "dist/logger.d.ts",
49
+ "dist/networks.js",
50
+ "dist/networks.d.ts",
51
+ "dist/osnma_source.js",
52
+ "dist/osnma_source.d.ts",
53
+ "dist/pool_registry.js",
54
+ "dist/pool_registry.d.ts",
55
+ "dist/pot_signer.js",
56
+ "dist/pot_signer.d.ts",
57
+ "dist/protocol_fee.js",
58
+ "dist/protocol_fee.d.ts",
59
+ "dist/revenue_tiers.js",
60
+ "dist/revenue_tiers.d.ts",
61
+ "dist/signer.js",
62
+ "dist/signer.d.ts",
63
+ "dist/time_synthesis.js",
64
+ "dist/time_synthesis.d.ts",
65
+ "dist/trust_store.js",
66
+ "dist/trust_store.d.ts",
67
+ "dist/ttt_builder.js",
68
+ "dist/ttt_builder.d.ts",
69
+ "dist/ttt_client.js",
70
+ "dist/ttt_client.d.ts",
71
+ "dist/types.js",
72
+ "dist/types.d.ts",
73
+ "dist/v4_hook.js",
74
+ "dist/v4_hook.d.ts",
75
+ "dist/x402_enforcer.js",
76
+ "dist/x402_enforcer.d.ts",
34
77
  "README.md"
35
78
  ],
36
79
  "scripts": {
@@ -1,59 +0,0 @@
1
- export declare enum AdaptiveMode {
2
- TURBO = "TURBO",// 50ms — Valid sequence, low latency
3
- FULL = "FULL"
4
- }
5
- export interface TTTRecord {
6
- time: number;
7
- txOrder: string[];
8
- grgPayload: Uint8Array[];
9
- }
10
- export interface Block {
11
- timestamp: number;
12
- txs: string[];
13
- data: Uint8Array;
14
- }
15
- /** Tier-based dynamic tolerance (ms) — auditor-requested upgrade */
16
- export declare const TIER_TOLERANCE_MS: Record<string, number>;
17
- export declare class AdaptiveSwitch {
18
- private windowSize;
19
- private threshold;
20
- private history;
21
- private currentMode;
22
- private minBlocks;
23
- private penaltyCooldown;
24
- private consecutiveFailures;
25
- private turboEntryThreshold;
26
- private turboMaintainThreshold;
27
- private tolerance;
28
- constructor(options?: {
29
- tolerance?: number;
30
- });
31
- /**
32
- * Core TTT mechanism: switches between Turbo/Full mode based on timestamp ordering match rate.
33
- */
34
- verifyBlock(block: Block, tttRecord: TTTRecord, chainId: number, poolAddress: string, tier?: string): AdaptiveMode;
35
- /**
36
- * Return fee discount rate based on current mode.
37
- * TURBO: 20% discount (incentivizes profitability).
38
- * FULL: No discount.
39
- */
40
- getFeeDiscount(): number;
41
- /**
42
- * Get current adaptive mode.
43
- */
44
- getCurrentMode(): AdaptiveMode;
45
- /**
46
- * Reset history (for testing).
47
- */
48
- reset(): void;
49
- /**
50
- * Serialize internal state to JSON for persistence across restarts.
51
- * Allows operators to avoid re-learning over 20 blocks after a restart.
52
- */
53
- serialize(): string;
54
- /**
55
- * Reconstruct an AdaptiveSwitch from previously serialized JSON state.
56
- */
57
- static deserialize(json: string): AdaptiveSwitch;
58
- private compareTransactionOrder;
59
- }
@@ -1,145 +0,0 @@
1
- "use strict";
2
- // sdk/src/adaptive_switch.ts — Adaptive Mode Switcher
3
- // Turbo (50ms) vs Full (127ms)
4
- Object.defineProperty(exports, "__esModule", { value: true });
5
- exports.AdaptiveSwitch = exports.TIER_TOLERANCE_MS = exports.AdaptiveMode = void 0;
6
- const grg_inverse_1 = require("./grg_inverse");
7
- const logger_1 = require("./logger");
8
- var AdaptiveMode;
9
- (function (AdaptiveMode) {
10
- AdaptiveMode["TURBO"] = "TURBO";
11
- AdaptiveMode["FULL"] = "FULL";
12
- })(AdaptiveMode || (exports.AdaptiveMode = AdaptiveMode = {}));
13
- // const TOLERANCE = 100; // 100ms tolerance for GEO-sat operator sync (now configurable via constructor)
14
- /** Tier-based dynamic tolerance (ms) — auditor-requested upgrade */
15
- exports.TIER_TOLERANCE_MS = {
16
- T0_epoch: 2000, // 6.4min tick → 2s tolerance
17
- T1_block: 200, // 2s tick → 200ms
18
- T2_slot: 500, // 12s tick → 500ms
19
- T3_micro: 10, // 100ms tick → 10ms (10%)
20
- };
21
- class AdaptiveSwitch {
22
- windowSize = 20; // B1-9: Updated from 10 to 20
23
- threshold = 0.9; // B1-9: Updated from 0.8 to 0.9
24
- history = [];
25
- currentMode = AdaptiveMode.FULL;
26
- minBlocks = 20; // B1-9: Minimum blocks for TURBO transition
27
- penaltyCooldown = 0; // B1-9: Penalty cooldown (P2-1: increased to 20 + exponential backoff)
28
- consecutiveFailures = 0; // P2-1: Track consecutive failures for exponential backoff
29
- turboEntryThreshold = 0.95; // P2-2: Hysteresis — stricter entry
30
- turboMaintainThreshold = 0.85; // P2-2: Hysteresis — relaxed maintenance
31
- tolerance;
32
- constructor(options) {
33
- this.tolerance = options?.tolerance ?? 100;
34
- }
35
- /**
36
- * Core TTT mechanism: switches between Turbo/Full mode based on timestamp ordering match rate.
37
- */
38
- verifyBlock(block, tttRecord, chainId, poolAddress, tier) {
39
- // 1. Check timestamp ordering and time match
40
- const orderMatch = this.compareTransactionOrder(block.txs, tttRecord.txOrder);
41
- const tolerance = tier ? (exports.TIER_TOLERANCE_MS[tier] ?? this.tolerance) : this.tolerance;
42
- const timeMatch = Math.abs(block.timestamp - tttRecord.time) < tolerance;
43
- let sequenceOk = orderMatch && timeMatch;
44
- // B1-1: Do not skip GrgInverse.verify() in TURBO mode
45
- // We check integrity regardless of mode
46
- const integrityOk = grg_inverse_1.GrgInverse.verify(block.data, tttRecord.grgPayload, chainId, poolAddress);
47
- if (!integrityOk) {
48
- logger_1.logger.error(`[AdaptiveSwitch] GRG integrity check FAILED`);
49
- sequenceOk = false; // Mark as false if integrity fails
50
- if (this.currentMode === AdaptiveMode.TURBO) {
51
- logger_1.logger.warn(`[AdaptiveSwitch] TURBO integrity failure: Penalty cooldown applied`);
52
- // P2-1: Exponential backoff — 20 * 2^(consecutiveFailures), capped at 320
53
- this.consecutiveFailures = Math.min(this.consecutiveFailures + 1, 4);
54
- this.penaltyCooldown = 20 * Math.pow(2, this.consecutiveFailures - 1); // 20, 40, 80, 160, 320
55
- }
56
- }
57
- // 2. Update history (Sliding Window)
58
- this.history.push(sequenceOk);
59
- if (this.history.length > this.windowSize) {
60
- this.history.shift();
61
- }
62
- if (this.penaltyCooldown > 0) {
63
- this.penaltyCooldown--;
64
- }
65
- // 3. Calculate match rate and switch mode
66
- const matchCount = this.history.filter(h => h).length;
67
- const matchRate = this.history.length > 0 ? matchCount / this.history.length : 0;
68
- // P2-2: Hysteresis — different thresholds for entering vs maintaining TURBO
69
- const effectiveThreshold = this.currentMode === AdaptiveMode.TURBO
70
- ? this.turboMaintainThreshold // 85% to stay in TURBO
71
- : this.turboEntryThreshold; // 95% to enter TURBO
72
- if (this.history.length >= this.minBlocks && matchRate >= effectiveThreshold && this.penaltyCooldown === 0) {
73
- if (this.currentMode === AdaptiveMode.FULL) {
74
- logger_1.logger.info(`[AdaptiveSwitch] Switching to TURBO mode (Match rate: ${(matchRate * 100).toFixed(1)}%, Entry threshold: ${(this.turboEntryThreshold * 100).toFixed(0)}%)`);
75
- }
76
- this.currentMode = AdaptiveMode.TURBO;
77
- this.consecutiveFailures = 0; // P2-1: Reset on successful TURBO
78
- }
79
- else {
80
- if (this.currentMode === AdaptiveMode.TURBO) {
81
- logger_1.logger.warn(`[AdaptiveSwitch] Switching to FULL mode (Match rate: ${(matchRate * 100).toFixed(1)}%, Maintain threshold: ${(this.turboMaintainThreshold * 100).toFixed(0)}%, Cooldown: ${this.penaltyCooldown})`);
82
- }
83
- this.currentMode = AdaptiveMode.FULL;
84
- }
85
- return this.currentMode;
86
- }
87
- /**
88
- * Return fee discount rate based on current mode.
89
- * TURBO: 20% discount (incentivizes profitability).
90
- * FULL: No discount.
91
- */
92
- getFeeDiscount() {
93
- return this.currentMode === AdaptiveMode.TURBO ? 0.2 : 0.0;
94
- }
95
- /**
96
- * Get current adaptive mode.
97
- */
98
- getCurrentMode() {
99
- return this.currentMode;
100
- }
101
- /**
102
- * Reset history (for testing).
103
- */
104
- reset() {
105
- this.history = [];
106
- this.currentMode = AdaptiveMode.FULL;
107
- this.penaltyCooldown = 0;
108
- this.consecutiveFailures = 0;
109
- }
110
- /**
111
- * Serialize internal state to JSON for persistence across restarts.
112
- * Allows operators to avoid re-learning over 20 blocks after a restart.
113
- */
114
- serialize() {
115
- return JSON.stringify({
116
- history: this.history,
117
- currentMode: this.currentMode,
118
- consecutiveFailures: this.consecutiveFailures,
119
- penaltyCooldown: this.penaltyCooldown,
120
- tolerance: this.tolerance,
121
- });
122
- }
123
- /**
124
- * Reconstruct an AdaptiveSwitch from previously serialized JSON state.
125
- */
126
- static deserialize(json) {
127
- const data = JSON.parse(json);
128
- const instance = new AdaptiveSwitch({ tolerance: data.tolerance ?? 100 });
129
- instance.history = data.history;
130
- instance.currentMode = data.currentMode;
131
- instance.consecutiveFailures = data.consecutiveFailures;
132
- instance.penaltyCooldown = data.penaltyCooldown;
133
- return instance;
134
- }
135
- compareTransactionOrder(blockTxs, expectedOrder) {
136
- if (blockTxs.length !== expectedOrder.length)
137
- return false;
138
- for (let i = 0; i < blockTxs.length; i++) {
139
- if (blockTxs[i] !== expectedOrder[i])
140
- return false;
141
- }
142
- return true;
143
- }
144
- }
145
- exports.AdaptiveSwitch = AdaptiveSwitch;
@@ -1,61 +0,0 @@
1
- import { TimeSynthesis } from "./time_synthesis";
2
- import { EVMConnector } from "./evm_connector";
3
- import { AutoMintConfig, MintResult } from "./types";
4
- /**
5
- * AutoMintEngine - Automatic TTT minting engine.
6
- * Combines time synthesis, dynamic fee calculation, and EVM minting into a single loop.
7
- */
8
- export declare class AutoMintEngine {
9
- private config;
10
- private timeSynthesis;
11
- private feeEngine;
12
- private evmConnector;
13
- private feeCollector;
14
- private timer;
15
- private isRunning;
16
- private isProcessing;
17
- private onMintCallback?;
18
- private onFailureCallback?;
19
- private onLatencyCallback?;
20
- private cachedSigner;
21
- private consecutiveFailures;
22
- private maxConsecutiveFailures;
23
- private potSigner;
24
- /** Monotonic counter appended to tokenId hash to prevent collision when two mints share the same nanosecond timestamp. */
25
- private mintNonce;
26
- /** Fire the GRG >50ms performance warning at most once per engine session. */
27
- private warnedGrgSlow;
28
- constructor(config: AutoMintConfig);
29
- getEvmConnector(): EVMConnector;
30
- getTimeSynthesis(): TimeSynthesis;
31
- setOnMint(callback: (result: MintResult) => void): void;
32
- setOnFailure(callback: (error: Error) => void): void;
33
- setOnLatency(callback: (ms: number) => void): void;
34
- /**
35
- * Initialize the engine (RPC connection and contract setup).
36
- */
37
- initialize(): Promise<void>;
38
- /**
39
- * Start the automatic minting loop.
40
- */
41
- start(): void;
42
- /**
43
- * Stop the automatic minting loop.
44
- */
45
- stop(): void;
46
- /**
47
- * Resume the minting loop after a circuit breaker trip.
48
- * Resets the consecutive failure counter and restarts the loop.
49
- */
50
- resume(): void;
51
- /**
52
- * Sleep helper for retry backoff.
53
- */
54
- private sleep;
55
- /**
56
- * Execute a single mint tick.
57
- * Time synthesis -> tokenId generation -> EVM mint call -> fee calculation/deduction.
58
- */
59
- mintTick(): Promise<void>;
60
- private signFeeMessage;
61
- }