@peridotvault/peridotbase-sdk 0.0.0-stage → 0.2.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/dist/v3.d.ts ADDED
@@ -0,0 +1,357 @@
1
+ /**
2
+ * v3 (record-PDA) client helpers.
3
+ *
4
+ * A v3 table stores one logical row per PDA, so the planner is deterministic:
5
+ *
6
+ * - primary-key equality → derive the record PDA, one `getAccountInfo`
7
+ * - UNIQUE equality → claim PDA → owner record
8
+ * - non-unique equality → posting lanes for the value → owner records
9
+ * - full scan → directory lanes/pages → record PDAs
10
+ *
11
+ * `scan()` is a resumable cursor over the on-chain directory. It never calls
12
+ * `getProgramAccounts` for row data and never materialises the whole table.
13
+ */
14
+ import { PublicKey } from "@solana/web3.js";
15
+ import type { PeridotBase } from "./client";
16
+ import { type SqlValue } from "./values";
17
+ /** Default result page size for `scan()`. */
18
+ export declare const DEFAULT_SCAN_PAGE = 500;
19
+ export interface V3StorageConfig {
20
+ epoch: bigint;
21
+ laneCount: number;
22
+ pageCap: number;
23
+ postingLanes: number;
24
+ /** Retained revisions per record; 0 disables append-only history. */
25
+ historyLimit: number;
26
+ /** Declarative partition routing; `null` hashes the digest onto a lane. */
27
+ partition: V3PartitionConfig | null;
28
+ }
29
+ /** RANGE/LIST partitioning on one BIGINT-like primary-key column. */
30
+ export interface V3PartitionConfig {
31
+ strategy: "range" | "list";
32
+ column: number;
33
+ /** RANGE: ascending exclusive upper bounds. LIST: listed values. */
34
+ bounds: bigint[];
35
+ /** Values outside every bound go to a final partition. */
36
+ hasDefault: boolean;
37
+ }
38
+ export interface V3Column {
39
+ name: string;
40
+ type: "bool" | "i64" | "decimal" | "text" | "uuid";
41
+ scale?: number;
42
+ maxLen?: number;
43
+ default?: SqlValue;
44
+ }
45
+ export interface V3Index {
46
+ indexId: bigint;
47
+ name: string;
48
+ column: number;
49
+ columns: number[];
50
+ /** Non-key columns stored in the index entry (covering index). */
51
+ includes: number[];
52
+ unique: boolean;
53
+ nullsNotDistinct: boolean;
54
+ }
55
+ /** Child-side foreign key: this table's columns point at a parent key. */
56
+ export interface V3ForeignKey {
57
+ column: number;
58
+ parentTable: PublicKey;
59
+ /** Parent column index; `0xff` for a legacy primary-key target. */
60
+ parentColumn: number;
61
+ /** Parent UNIQUE index id; `0n` for a primary-key target. */
62
+ parentIndexId: bigint;
63
+ /** Child columns in parent-index order; `[column]` for single-column FKs. */
64
+ childColumns: number[];
65
+ /** `0` = MATCH SIMPLE, `1` = MATCH FULL. */
66
+ matchType: number;
67
+ }
68
+ /** Parent-side inbound foreign key: one of this table's columns is referenced. */
69
+ export interface V3InboundForeignKey {
70
+ childTable: PublicKey;
71
+ fkId: bigint;
72
+ parentColumn: number;
73
+ parentIndexId: bigint;
74
+ childColumn: number;
75
+ }
76
+ export interface V3Record {
77
+ address: PublicKey;
78
+ revision: bigint;
79
+ live: boolean;
80
+ values: SqlValue[];
81
+ accruedFee: bigint;
82
+ }
83
+ /** Opaque traversal cursor: lane/page/entry plus the epoch it belongs to. */
84
+ export interface V3Cursor {
85
+ epoch: string;
86
+ lane: number;
87
+ page: bigint;
88
+ entry: number;
89
+ }
90
+ export interface V3ScanPage {
91
+ rows: V3Record[];
92
+ cursor: V3Cursor | null;
93
+ /** True when the traversal reached the last lane. */
94
+ done: boolean;
95
+ }
96
+ export interface RawDirectoryLane {
97
+ table: PublicKey;
98
+ epoch: bigint;
99
+ lane: number;
100
+ tailPage: bigint;
101
+ entries: bigint;
102
+ }
103
+ export declare function decodeDirectoryLane(data: Buffer): RawDirectoryLane;
104
+ export interface RawDirectoryPage {
105
+ lane: number;
106
+ page: bigint;
107
+ digests: Uint8Array[];
108
+ }
109
+ export declare function decodeDirectoryPage(data: Buffer): RawDirectoryPage;
110
+ export interface RawClaim {
111
+ key: Uint8Array;
112
+ covering: Buffer;
113
+ owner: PublicKey;
114
+ }
115
+ export declare function decodeUniqueClaim(data: Buffer): RawClaim;
116
+ export interface RawPostingPage {
117
+ lane: number;
118
+ members: {
119
+ record: PublicKey;
120
+ slot: number;
121
+ live: boolean;
122
+ covering: Buffer;
123
+ }[];
124
+ }
125
+ export declare function decodePostingPage(data: Buffer): RawPostingPage;
126
+ export declare class V3Table {
127
+ private readonly client;
128
+ readonly address: PublicKey;
129
+ readonly tableId: bigint;
130
+ readonly storage: PublicKey;
131
+ readonly config: V3StorageConfig;
132
+ readonly columns: V3Column[];
133
+ readonly primaryKey: number;
134
+ readonly primaryKeyColumns: number[];
135
+ readonly indexes: V3Index[];
136
+ readonly foreignKeys: V3ForeignKey[];
137
+ readonly inboundForeignKeys: V3InboundForeignKey[];
138
+ private constructor();
139
+ private readonly parentEpochs;
140
+ /** Loads the table catalog and its v3 storage descriptor. */
141
+ static load(client: PeridotBase, tableId: number | bigint | PublicKey): Promise<V3Table>;
142
+ /** Canonical primary-key digest used for the record PDA and directory lane. */
143
+ digestOf(primaryKey: SqlValue | SqlValue[]): Buffer;
144
+ /**
145
+ * Partition index for a row, or `null` when the table is unpartitioned.
146
+ * The partition column is a primary-key column, so this value never changes
147
+ * for an existing row.
148
+ */
149
+ partitionOf(values: SqlValue[]): number | null;
150
+ /** Number of declared partitions, including the optional default one. */
151
+ get partitionCount(): number;
152
+ private canonicalPk;
153
+ recordAddress(primaryKey: SqlValue | SqlValue[]): PublicKey;
154
+ /** Direct primary-key lookup: one account fetch, no directory or index walk. */
155
+ get(primaryKey: SqlValue | SqlValue[]): Promise<V3Record | null>;
156
+ private decodeRecord;
157
+ /**
158
+ * Ensures the directory lane/page that the next append targets exists, and
159
+ * returns both addresses. A full tail page triggers a rollover.
160
+ */
161
+ ensureDirectory(digest: Uint8Array, values?: SqlValue[]): Promise<{
162
+ lane: number;
163
+ lanePda: PublicKey;
164
+ pagePda: PublicKey;
165
+ page: bigint;
166
+ }>;
167
+ private createDirPage;
168
+ /** Claim and posting accounts a mutation must supply, all pre-derived. */
169
+ indexAccounts(values: SqlValue[], digest: Uint8Array): PublicKey[];
170
+ /**
171
+ * Audit accounts for a mutation. When the database enforces auditing the
172
+ * program rejects a write without them, so this reads the trail head and
173
+ * derives the event PDA for the next sequence.
174
+ */
175
+ private auditAccounts;
176
+ /**
177
+ * History accounts for a mutation. Returns nulls when the table keeps no
178
+ * history; otherwise the account for the superseded revision plus the one
179
+ * leaving the retention window (closed on-chain).
180
+ */
181
+ private historyAccounts;
182
+ /** Coerces a partial row into a full, schema-aligned value vector. */
183
+ coerceRow(row: Record<string, SqlValue>): SqlValue[];
184
+ private parentEpoch;
185
+ /**
186
+ * Parent helper accounts for child-side foreign keys: parent storage, the
187
+ * referenced record (PK target) or UNIQUE claim, and the writable counter.
188
+ * Old and new tuples are unioned so an FK move is one transaction.
189
+ */
190
+ private foreignKeyAccounts;
191
+ /** Writable counters for every inbound FK tuple an update/delete removes. */
192
+ private inboundForeignKeyAccounts;
193
+ /** Writable helper that routes mutation fees to the sponsor allowance. */
194
+ private sponsorAllowanceAccount;
195
+ /**
196
+ * Inserts one row. One record per transaction; no implicit batching.
197
+ *
198
+ * A tombstoned identity is revived with `reinsert_record_v3`, which keeps the
199
+ * same PDA/directory slot and increments the revision (PRD §3.1). The create
200
+ * path is attempted first so the common case costs no extra RPC.
201
+ */
202
+ insert(row: Record<string, SqlValue>): Promise<{
203
+ address: PublicKey;
204
+ signature: string;
205
+ }>;
206
+ /** Updates one row using its current revision as the optimistic lock. */
207
+ update(primaryKey: SqlValue | SqlValue[], assignments: {
208
+ column: string | number;
209
+ value: SqlValue;
210
+ }[]): Promise<string>;
211
+ /** Tombstones one row. The address and revision history are preserved. */
212
+ /**
213
+ * Atomic counter increment: reads the record, applies `delta`, and submits an
214
+ * update with the observed revision. A concurrent writer causes a retry.
215
+ */
216
+ increment(primaryKey: SqlValue | SqlValue[], column: string | number, delta?: bigint, retries?: number): Promise<bigint>;
217
+ delete(primaryKey: SqlValue | SqlValue[]): Promise<string>;
218
+ /** UNIQUE equality lookup: claim → owner record → recheck. */
219
+ lookupUnique(indexName: string, value: SqlValue): Promise<V3Record | null>;
220
+ /** Non-unique equality lookup: union every posting lane for the value. */
221
+ lookupIndex(indexName: string, value: SqlValue): Promise<V3Record[]>;
222
+ /**
223
+ * Reverse foreign-key lookup: rows of a child table that reference this row.
224
+ * Uses a child index on the FK column when one exists, otherwise scans the
225
+ * child table (bounded by `limit`).
226
+ */
227
+ childrenOf(fkId: number | bigint, parentKey: SqlValue, options?: {
228
+ limit?: number;
229
+ }): Promise<{
230
+ childTableId: string;
231
+ rows: Record<string, SqlValue>[];
232
+ }>;
233
+ /** Column indices an index can answer without reading the record. */
234
+ coveredColumns(index: V3Index): number[];
235
+ /**
236
+ * Planner for an equality lookup. `COVERING_INDEX_ONLY` means every requested
237
+ * column is in the index key or its INCLUDE payload, so the record accounts
238
+ * are never fetched.
239
+ */
240
+ explainLookup(indexName: string, columns: string[]): Promise<{
241
+ strategy: "COVERING_INDEX_ONLY" | "INDEX_LOOKUP";
242
+ index: string;
243
+ uncovered: string[];
244
+ }>;
245
+ /**
246
+ * Equality lookup served from the index alone. Returns `null` when the index
247
+ * does not cover every requested column (or when an entry predates covering
248
+ * payloads), so the caller falls back to `lookupIndex` + record fetch.
249
+ */
250
+ lookupIndexCovered(indexName: string, value: SqlValue, columns: string[]): Promise<Record<string, SqlValue>[] | null>;
251
+ /**
252
+ * Resumable directory scan. Returns at most `limit` live rows and a cursor
253
+ * that resumes exactly after the last visited entry. Tombstones are skipped
254
+ * but still advance the cursor.
255
+ */
256
+ /**
257
+ * Bounded traversal over the frozen directory.
258
+ *
259
+ * Lane headers, directory pages and record accounts are all fetched with
260
+ * `getMultipleAccounts` (100 addresses per request). A row is only emitted
261
+ * after its record account was read, so a missing page below the committed
262
+ * tail is an integrity error rather than a silent skip.
263
+ */
264
+ scan(options?: {
265
+ limit?: number;
266
+ cursor?: V3Cursor | null;
267
+ partition?: number;
268
+ }): Promise<V3ScanPage>;
269
+ /**
270
+ * Gate account for Member writes, or null for the owner/admin path.
271
+ *
272
+ * Only an organization member without an elevated project grant must record
273
+ * the external-write evidence, and the first such insert creates the gate
274
+ * atomically with the record (PRD §6.2).
275
+ */
276
+ private externalGateAccount;
277
+ /** `query.page()` equivalent: one bounded page of results. */
278
+ page(options?: {
279
+ limit?: number;
280
+ cursor?: V3Cursor | null;
281
+ partition?: number;
282
+ }): Promise<V3ScanPage>;
283
+ /** `query.stream()` equivalent: yields rows without materializing the table. */
284
+ stream(options?: {
285
+ limit?: number;
286
+ partition?: number;
287
+ }): AsyncGenerator<V3Record>;
288
+ private fetchOneLane;
289
+ /** Drains `scan()` into memory, honouring a hard cap. */
290
+ scanAll(options?: {
291
+ cap?: number;
292
+ partition?: number;
293
+ }): Promise<V3Record[]>;
294
+ /**
295
+ * Raw-state invariant audit (PRD §12).
296
+ *
297
+ * Re-derives everything from directory/record/claim/posting accounts, never
298
+ * from SDK caches: one directory slot per identity, no duplicate digest, no
299
+ * missing record below the committed tail, locator agreement, exactly one
300
+ * LIVE claim per LIVE unique value, and exactly one LIVE posting membership
301
+ * per LIVE indexed value.
302
+ */
303
+ auditInvariants(): Promise<V3InvariantReport>;
304
+ private fetchBatched;
305
+ }
306
+ export interface V3MigrationResult {
307
+ pages: number;
308
+ rows: number;
309
+ manifest: PublicKey;
310
+ signatures: string[];
311
+ }
312
+ /**
313
+ * Copies a frozen v2 table into this v3 table.
314
+ *
315
+ * The caller must pause the protocol first: `paused` is the program-enforced
316
+ * write freeze, and both v2 DML and these migration instructions reject writes
317
+ * while it is set. Every row is read from the on-chain v2 page by the program,
318
+ * so this driver only supplies addresses and slot numbers.
319
+ */
320
+ export declare function migrateV2TableToV3(client: PeridotBase, tableId: number | bigint, options?: {
321
+ resume?: boolean;
322
+ }): Promise<V3MigrationResult>;
323
+ export interface V3CoverageResult {
324
+ pages: number;
325
+ rows: number;
326
+ signatures: string[];
327
+ }
328
+ /**
329
+ * Re-reads every copied v2 row from v3 and advances the manifest checkpoint.
330
+ *
331
+ * The program recomputes each PK digest and requires a LIVE record with the same
332
+ * digest, so a client cannot declare coverage it did not actually achieve.
333
+ */
334
+ export declare function verifyV3Coverage(client: PeridotBase, tableId: number | bigint): Promise<V3CoverageResult>;
335
+ /**
336
+ * Atomic cutover: publishes the v3 storage and retires the v2 layout in one
337
+ * transaction. Requires a READY manifest with complete coverage and a paused
338
+ * protocol.
339
+ */
340
+ export declare function activateV3Table(client: PeridotBase, tableId: number | bigint): Promise<{
341
+ activation: PublicKey;
342
+ signature: string;
343
+ }>;
344
+ export interface V3InvariantReport {
345
+ directoryEntries: number;
346
+ liveRecords: number;
347
+ tombstones: number;
348
+ duplicateDirectoryDigests: string[];
349
+ missingRecords: string[];
350
+ locatorMismatches: string[];
351
+ revisionProblems: string[];
352
+ uniqueClaimProblems: string[];
353
+ postingProblems: string[];
354
+ checkedConstraints: boolean;
355
+ }
356
+ /** Convenience wrapper: loads the table and audits its raw on-chain state. */
357
+ export declare function verifyV3Invariants(client: PeridotBase, tableId: number | bigint): Promise<V3InvariantReport>;