@arkade-os/swap 0.0.5 → 0.0.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +79 -10
- package/dist/chunk-WGRU2DBF.js +38 -0
- package/dist/{chunk-Q4FAYBXS.js → chunk-ZDTRQZE2.js} +49 -15
- package/dist/index.cjs +103 -14
- package/dist/index.d.cts +46 -231
- package/dist/index.d.ts +46 -231
- package/dist/index.js +62 -35
- package/dist/nostr.cjs +15 -9
- package/dist/nostr.d.cts +4 -3
- package/dist/nostr.d.ts +4 -3
- package/dist/nostr.js +4 -11
- package/dist/repositories/realm/index.cjs +138 -0
- package/dist/repositories/realm/index.d.cts +103 -0
- package/dist/repositories/realm/index.d.ts +103 -0
- package/dist/repositories/realm/index.js +108 -0
- package/dist/repositories/sqlite/index.cjs +163 -0
- package/dist/repositories/sqlite/index.d.cts +63 -0
- package/dist/repositories/sqlite/index.d.ts +63 -0
- package/dist/repositories/sqlite/index.js +138 -0
- package/dist/repository-BwnZ8N62.d.cts +236 -0
- package/dist/repository-BwnZ8N62.d.ts +236 -0
- package/dist/{rfq-BH2yvo3O.d.cts → rfq-DfT9dAss.d.cts} +24 -11
- package/dist/{rfq-BH2yvo3O.d.ts → rfq-DfT9dAss.d.ts} +24 -11
- package/package.json +24 -4
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/repositories/sqlite/index.ts
|
|
21
|
+
var sqlite_exports = {};
|
|
22
|
+
__export(sqlite_exports, {
|
|
23
|
+
SQLiteAssetSwapRepository: () => SQLiteAssetSwapRepository
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(sqlite_exports);
|
|
26
|
+
|
|
27
|
+
// src/repositories/sqlite/repository.ts
|
|
28
|
+
var import_sqlite = require("@arkade-os/sdk/repositories/sqlite");
|
|
29
|
+
|
|
30
|
+
// src/repository.ts
|
|
31
|
+
var marketsCacheKey = (network, registry) => `arkade-intents-markets-${network}-${registry}`;
|
|
32
|
+
|
|
33
|
+
// src/repositories/sqlite/repository.ts
|
|
34
|
+
var DEFAULT_PREFIX = "arkade_";
|
|
35
|
+
var INSERT_CHUNK = 500;
|
|
36
|
+
var SQLiteAssetSwapRepository = class {
|
|
37
|
+
constructor(db, options) {
|
|
38
|
+
this.db = db;
|
|
39
|
+
this.prefix = (0, import_sqlite.sanitizeTablePrefix)(options?.prefix ?? DEFAULT_PREFIX);
|
|
40
|
+
this.swaps = `${this.prefix}asset_swaps`;
|
|
41
|
+
this.scanned = `${this.prefix}asset_swap_scanned_txids`;
|
|
42
|
+
this.markets = `${this.prefix}asset_swap_markets`;
|
|
43
|
+
}
|
|
44
|
+
db;
|
|
45
|
+
version = 2;
|
|
46
|
+
initPromise = null;
|
|
47
|
+
prefix;
|
|
48
|
+
swaps;
|
|
49
|
+
scanned;
|
|
50
|
+
markets;
|
|
51
|
+
/** A rejected init is not cached. The DDL runs in a transaction on a shared
|
|
52
|
+
* connection, so it can fail for reasons that pass — a `SQLITE_BUSY` on
|
|
53
|
+
* `BEGIN IMMEDIATE`, a neighbour's rollback — and caching that rejection
|
|
54
|
+
* would strand the instance unusable for the life of the process. Same rule
|
|
55
|
+
* as the IndexedDB backend's `ensureDb`. */
|
|
56
|
+
ensureInit() {
|
|
57
|
+
return this.initPromise ??= this.init().catch((err) => {
|
|
58
|
+
this.initPromise = null;
|
|
59
|
+
throw err;
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
/** The DDL is transactional in SQLite too: run raw on a shared connection it
|
|
63
|
+
* would join a neighbour's open transaction and vanish with its rollback,
|
|
64
|
+
* while `initPromise` stayed resolved and every later statement failed with
|
|
65
|
+
* `no such table`. */
|
|
66
|
+
async init() {
|
|
67
|
+
await this.withTx(async () => {
|
|
68
|
+
await this.db.run(`CREATE TABLE IF NOT EXISTS ${this.swaps} (
|
|
69
|
+
id TEXT PRIMARY KEY,
|
|
70
|
+
status TEXT NOT NULL,
|
|
71
|
+
created_at INTEGER NOT NULL,
|
|
72
|
+
data TEXT NOT NULL
|
|
73
|
+
)`);
|
|
74
|
+
await this.db.run(
|
|
75
|
+
`CREATE INDEX IF NOT EXISTS idx_${this.prefix}asset_swaps_status ON ${this.swaps} (status)`
|
|
76
|
+
);
|
|
77
|
+
await this.db.run(
|
|
78
|
+
`CREATE INDEX IF NOT EXISTS idx_${this.prefix}asset_swaps_created_at ON ${this.swaps} (created_at)`
|
|
79
|
+
);
|
|
80
|
+
await this.db.run(`CREATE TABLE IF NOT EXISTS ${this.scanned} (txid TEXT PRIMARY KEY)`);
|
|
81
|
+
await this.db.run(
|
|
82
|
+
`CREATE TABLE IF NOT EXISTS ${this.markets} (cache_key TEXT PRIMARY KEY, data TEXT NOT NULL)`
|
|
83
|
+
);
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
/** Every write, including the single-statement ones. The chain serializes
|
|
87
|
+
* transaction *blocks*, not bare statements: one issued between a
|
|
88
|
+
* neighbour's BEGIN IMMEDIATE and its COMMIT becomes part of that
|
|
89
|
+
* transaction and dies with it. `fn` must issue only raw db calls — no
|
|
90
|
+
* repository method, no `ensureInit` — since `runInTransaction` cannot
|
|
91
|
+
* nest. */
|
|
92
|
+
withTx(fn) {
|
|
93
|
+
return (0, import_sqlite.runInTransaction)(this.db, fn);
|
|
94
|
+
}
|
|
95
|
+
async saveSwap(swap) {
|
|
96
|
+
await this.ensureInit();
|
|
97
|
+
await this.withTx(async () => {
|
|
98
|
+
await this.db.run(
|
|
99
|
+
`INSERT OR REPLACE INTO ${this.swaps} (id, status, created_at, data)
|
|
100
|
+
VALUES (?, ?, ?, ?)`,
|
|
101
|
+
[swap.id, swap.status, swap.createdAt, JSON.stringify(swap)]
|
|
102
|
+
);
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
async getAllSwaps() {
|
|
106
|
+
await this.ensureInit();
|
|
107
|
+
const rows = await this.db.all(`SELECT data FROM ${this.swaps}`);
|
|
108
|
+
return rows.map((r) => JSON.parse(r.data));
|
|
109
|
+
}
|
|
110
|
+
async getScannedTxids() {
|
|
111
|
+
await this.ensureInit();
|
|
112
|
+
const rows = await this.db.all(`SELECT txid FROM ${this.scanned}`);
|
|
113
|
+
return new Set(rows.map((r) => r.txid));
|
|
114
|
+
}
|
|
115
|
+
async markTxidsScanned(txids) {
|
|
116
|
+
await this.ensureInit();
|
|
117
|
+
const all = [...txids];
|
|
118
|
+
if (all.length === 0) return;
|
|
119
|
+
await this.withTx(async () => {
|
|
120
|
+
for (let i = 0; i < all.length; i += INSERT_CHUNK) {
|
|
121
|
+
const chunk = all.slice(i, i + INSERT_CHUNK);
|
|
122
|
+
await this.db.run(
|
|
123
|
+
`INSERT OR IGNORE INTO ${this.scanned} (txid) VALUES ${chunk.map(() => "(?)").join(", ")}`,
|
|
124
|
+
chunk
|
|
125
|
+
);
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
async getCachedMarkets(network, registry) {
|
|
130
|
+
await this.ensureInit();
|
|
131
|
+
const row = await this.db.get(
|
|
132
|
+
`SELECT data FROM ${this.markets} WHERE cache_key = ?`,
|
|
133
|
+
[marketsCacheKey(network, registry)]
|
|
134
|
+
);
|
|
135
|
+
return row ? JSON.parse(row.data) : void 0;
|
|
136
|
+
}
|
|
137
|
+
async saveCachedMarkets(network, registry, entry) {
|
|
138
|
+
await this.ensureInit();
|
|
139
|
+
await this.withTx(async () => {
|
|
140
|
+
await this.db.run(
|
|
141
|
+
`INSERT OR REPLACE INTO ${this.markets} (cache_key, data) VALUES (?, ?)`,
|
|
142
|
+
[marketsCacheKey(network, registry), JSON.stringify(entry)]
|
|
143
|
+
);
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
/** All three tables in one transaction: clearing swaps but keeping scanned
|
|
147
|
+
* txids would leave the restore scan permanently skipping those funding
|
|
148
|
+
* txs, so a partial clear must not be observable. */
|
|
149
|
+
async clear() {
|
|
150
|
+
await this.ensureInit();
|
|
151
|
+
await this.withTx(async () => {
|
|
152
|
+
await this.db.run(`DELETE FROM ${this.swaps}`);
|
|
153
|
+
await this.db.run(`DELETE FROM ${this.scanned}`);
|
|
154
|
+
await this.db.run(`DELETE FROM ${this.markets}`);
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
async [Symbol.asyncDispose]() {
|
|
158
|
+
}
|
|
159
|
+
};
|
|
160
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
161
|
+
0 && (module.exports = {
|
|
162
|
+
SQLiteAssetSwapRepository
|
|
163
|
+
});
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { SQLExecutor } from '@arkade-os/sdk/repositories/sqlite';
|
|
2
|
+
import { A as AssetSwapRepository, a as AssetSwap, M as MarketsCacheEntry } from '../../repository-BwnZ8N62.cjs';
|
|
3
|
+
import '@arkade-os/solver-discovery';
|
|
4
|
+
import '@arkade-os/sdk';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* SQLite backend over the SDK's `SQLExecutor`, so any driver plugs in
|
|
8
|
+
* (expo-sqlite on React Native, better-sqlite3, node:sqlite).
|
|
9
|
+
*
|
|
10
|
+
* **Records are serialized as JSON**, whole, into a `data` column — `status`
|
|
11
|
+
* and `created_at` are mapped out for querying only, so no field of a record
|
|
12
|
+
* can be dropped. That holds for JSON-safe values: a consumer-added `Date`
|
|
13
|
+
* comes back a string and a `bigint` throws on save, unlike the IndexedDB
|
|
14
|
+
* backend's structured clone. `AssetSwap` itself is JSON-safe by design.
|
|
15
|
+
*
|
|
16
|
+
* Tables are created lazily on first operation. The consumer owns the
|
|
17
|
+
* `SQLExecutor` lifecycle — `[Symbol.asyncDispose]` is a no-op — and must pass
|
|
18
|
+
* the **same executor instance** to every repository on the database: the
|
|
19
|
+
* write chain is keyed by that object, and a per-repository literal splits it.
|
|
20
|
+
*/
|
|
21
|
+
declare class SQLiteAssetSwapRepository implements AssetSwapRepository {
|
|
22
|
+
private readonly db;
|
|
23
|
+
readonly version: 2;
|
|
24
|
+
private initPromise;
|
|
25
|
+
private readonly prefix;
|
|
26
|
+
private readonly swaps;
|
|
27
|
+
private readonly scanned;
|
|
28
|
+
private readonly markets;
|
|
29
|
+
constructor(db: SQLExecutor, options?: {
|
|
30
|
+
prefix?: string;
|
|
31
|
+
});
|
|
32
|
+
/** A rejected init is not cached. The DDL runs in a transaction on a shared
|
|
33
|
+
* connection, so it can fail for reasons that pass — a `SQLITE_BUSY` on
|
|
34
|
+
* `BEGIN IMMEDIATE`, a neighbour's rollback — and caching that rejection
|
|
35
|
+
* would strand the instance unusable for the life of the process. Same rule
|
|
36
|
+
* as the IndexedDB backend's `ensureDb`. */
|
|
37
|
+
private ensureInit;
|
|
38
|
+
/** The DDL is transactional in SQLite too: run raw on a shared connection it
|
|
39
|
+
* would join a neighbour's open transaction and vanish with its rollback,
|
|
40
|
+
* while `initPromise` stayed resolved and every later statement failed with
|
|
41
|
+
* `no such table`. */
|
|
42
|
+
private init;
|
|
43
|
+
/** Every write, including the single-statement ones. The chain serializes
|
|
44
|
+
* transaction *blocks*, not bare statements: one issued between a
|
|
45
|
+
* neighbour's BEGIN IMMEDIATE and its COMMIT becomes part of that
|
|
46
|
+
* transaction and dies with it. `fn` must issue only raw db calls — no
|
|
47
|
+
* repository method, no `ensureInit` — since `runInTransaction` cannot
|
|
48
|
+
* nest. */
|
|
49
|
+
private withTx;
|
|
50
|
+
saveSwap(swap: AssetSwap): Promise<void>;
|
|
51
|
+
getAllSwaps(): Promise<AssetSwap[]>;
|
|
52
|
+
getScannedTxids(): Promise<Set<string>>;
|
|
53
|
+
markTxidsScanned(txids: Iterable<string>): Promise<void>;
|
|
54
|
+
getCachedMarkets(network: string, registry: string): Promise<MarketsCacheEntry | undefined>;
|
|
55
|
+
saveCachedMarkets(network: string, registry: string, entry: MarketsCacheEntry): Promise<void>;
|
|
56
|
+
/** All three tables in one transaction: clearing swaps but keeping scanned
|
|
57
|
+
* txids would leave the restore scan permanently skipping those funding
|
|
58
|
+
* txs, so a partial clear must not be observable. */
|
|
59
|
+
clear(): Promise<void>;
|
|
60
|
+
[Symbol.asyncDispose](): Promise<void>;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export { SQLiteAssetSwapRepository };
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { SQLExecutor } from '@arkade-os/sdk/repositories/sqlite';
|
|
2
|
+
import { A as AssetSwapRepository, a as AssetSwap, M as MarketsCacheEntry } from '../../repository-BwnZ8N62.js';
|
|
3
|
+
import '@arkade-os/solver-discovery';
|
|
4
|
+
import '@arkade-os/sdk';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* SQLite backend over the SDK's `SQLExecutor`, so any driver plugs in
|
|
8
|
+
* (expo-sqlite on React Native, better-sqlite3, node:sqlite).
|
|
9
|
+
*
|
|
10
|
+
* **Records are serialized as JSON**, whole, into a `data` column — `status`
|
|
11
|
+
* and `created_at` are mapped out for querying only, so no field of a record
|
|
12
|
+
* can be dropped. That holds for JSON-safe values: a consumer-added `Date`
|
|
13
|
+
* comes back a string and a `bigint` throws on save, unlike the IndexedDB
|
|
14
|
+
* backend's structured clone. `AssetSwap` itself is JSON-safe by design.
|
|
15
|
+
*
|
|
16
|
+
* Tables are created lazily on first operation. The consumer owns the
|
|
17
|
+
* `SQLExecutor` lifecycle — `[Symbol.asyncDispose]` is a no-op — and must pass
|
|
18
|
+
* the **same executor instance** to every repository on the database: the
|
|
19
|
+
* write chain is keyed by that object, and a per-repository literal splits it.
|
|
20
|
+
*/
|
|
21
|
+
declare class SQLiteAssetSwapRepository implements AssetSwapRepository {
|
|
22
|
+
private readonly db;
|
|
23
|
+
readonly version: 2;
|
|
24
|
+
private initPromise;
|
|
25
|
+
private readonly prefix;
|
|
26
|
+
private readonly swaps;
|
|
27
|
+
private readonly scanned;
|
|
28
|
+
private readonly markets;
|
|
29
|
+
constructor(db: SQLExecutor, options?: {
|
|
30
|
+
prefix?: string;
|
|
31
|
+
});
|
|
32
|
+
/** A rejected init is not cached. The DDL runs in a transaction on a shared
|
|
33
|
+
* connection, so it can fail for reasons that pass — a `SQLITE_BUSY` on
|
|
34
|
+
* `BEGIN IMMEDIATE`, a neighbour's rollback — and caching that rejection
|
|
35
|
+
* would strand the instance unusable for the life of the process. Same rule
|
|
36
|
+
* as the IndexedDB backend's `ensureDb`. */
|
|
37
|
+
private ensureInit;
|
|
38
|
+
/** The DDL is transactional in SQLite too: run raw on a shared connection it
|
|
39
|
+
* would join a neighbour's open transaction and vanish with its rollback,
|
|
40
|
+
* while `initPromise` stayed resolved and every later statement failed with
|
|
41
|
+
* `no such table`. */
|
|
42
|
+
private init;
|
|
43
|
+
/** Every write, including the single-statement ones. The chain serializes
|
|
44
|
+
* transaction *blocks*, not bare statements: one issued between a
|
|
45
|
+
* neighbour's BEGIN IMMEDIATE and its COMMIT becomes part of that
|
|
46
|
+
* transaction and dies with it. `fn` must issue only raw db calls — no
|
|
47
|
+
* repository method, no `ensureInit` — since `runInTransaction` cannot
|
|
48
|
+
* nest. */
|
|
49
|
+
private withTx;
|
|
50
|
+
saveSwap(swap: AssetSwap): Promise<void>;
|
|
51
|
+
getAllSwaps(): Promise<AssetSwap[]>;
|
|
52
|
+
getScannedTxids(): Promise<Set<string>>;
|
|
53
|
+
markTxidsScanned(txids: Iterable<string>): Promise<void>;
|
|
54
|
+
getCachedMarkets(network: string, registry: string): Promise<MarketsCacheEntry | undefined>;
|
|
55
|
+
saveCachedMarkets(network: string, registry: string, entry: MarketsCacheEntry): Promise<void>;
|
|
56
|
+
/** All three tables in one transaction: clearing swaps but keeping scanned
|
|
57
|
+
* txids would leave the restore scan permanently skipping those funding
|
|
58
|
+
* txs, so a partial clear must not be observable. */
|
|
59
|
+
clear(): Promise<void>;
|
|
60
|
+
[Symbol.asyncDispose](): Promise<void>;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export { SQLiteAssetSwapRepository };
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import {
|
|
2
|
+
marketsCacheKey
|
|
3
|
+
} from "../../chunk-WGRU2DBF.js";
|
|
4
|
+
|
|
5
|
+
// src/repositories/sqlite/repository.ts
|
|
6
|
+
import {
|
|
7
|
+
runInTransaction,
|
|
8
|
+
sanitizeTablePrefix
|
|
9
|
+
} from "@arkade-os/sdk/repositories/sqlite";
|
|
10
|
+
var DEFAULT_PREFIX = "arkade_";
|
|
11
|
+
var INSERT_CHUNK = 500;
|
|
12
|
+
var SQLiteAssetSwapRepository = class {
|
|
13
|
+
constructor(db, options) {
|
|
14
|
+
this.db = db;
|
|
15
|
+
this.prefix = sanitizeTablePrefix(options?.prefix ?? DEFAULT_PREFIX);
|
|
16
|
+
this.swaps = `${this.prefix}asset_swaps`;
|
|
17
|
+
this.scanned = `${this.prefix}asset_swap_scanned_txids`;
|
|
18
|
+
this.markets = `${this.prefix}asset_swap_markets`;
|
|
19
|
+
}
|
|
20
|
+
db;
|
|
21
|
+
version = 2;
|
|
22
|
+
initPromise = null;
|
|
23
|
+
prefix;
|
|
24
|
+
swaps;
|
|
25
|
+
scanned;
|
|
26
|
+
markets;
|
|
27
|
+
/** A rejected init is not cached. The DDL runs in a transaction on a shared
|
|
28
|
+
* connection, so it can fail for reasons that pass — a `SQLITE_BUSY` on
|
|
29
|
+
* `BEGIN IMMEDIATE`, a neighbour's rollback — and caching that rejection
|
|
30
|
+
* would strand the instance unusable for the life of the process. Same rule
|
|
31
|
+
* as the IndexedDB backend's `ensureDb`. */
|
|
32
|
+
ensureInit() {
|
|
33
|
+
return this.initPromise ??= this.init().catch((err) => {
|
|
34
|
+
this.initPromise = null;
|
|
35
|
+
throw err;
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
/** The DDL is transactional in SQLite too: run raw on a shared connection it
|
|
39
|
+
* would join a neighbour's open transaction and vanish with its rollback,
|
|
40
|
+
* while `initPromise` stayed resolved and every later statement failed with
|
|
41
|
+
* `no such table`. */
|
|
42
|
+
async init() {
|
|
43
|
+
await this.withTx(async () => {
|
|
44
|
+
await this.db.run(`CREATE TABLE IF NOT EXISTS ${this.swaps} (
|
|
45
|
+
id TEXT PRIMARY KEY,
|
|
46
|
+
status TEXT NOT NULL,
|
|
47
|
+
created_at INTEGER NOT NULL,
|
|
48
|
+
data TEXT NOT NULL
|
|
49
|
+
)`);
|
|
50
|
+
await this.db.run(
|
|
51
|
+
`CREATE INDEX IF NOT EXISTS idx_${this.prefix}asset_swaps_status ON ${this.swaps} (status)`
|
|
52
|
+
);
|
|
53
|
+
await this.db.run(
|
|
54
|
+
`CREATE INDEX IF NOT EXISTS idx_${this.prefix}asset_swaps_created_at ON ${this.swaps} (created_at)`
|
|
55
|
+
);
|
|
56
|
+
await this.db.run(`CREATE TABLE IF NOT EXISTS ${this.scanned} (txid TEXT PRIMARY KEY)`);
|
|
57
|
+
await this.db.run(
|
|
58
|
+
`CREATE TABLE IF NOT EXISTS ${this.markets} (cache_key TEXT PRIMARY KEY, data TEXT NOT NULL)`
|
|
59
|
+
);
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
/** Every write, including the single-statement ones. The chain serializes
|
|
63
|
+
* transaction *blocks*, not bare statements: one issued between a
|
|
64
|
+
* neighbour's BEGIN IMMEDIATE and its COMMIT becomes part of that
|
|
65
|
+
* transaction and dies with it. `fn` must issue only raw db calls — no
|
|
66
|
+
* repository method, no `ensureInit` — since `runInTransaction` cannot
|
|
67
|
+
* nest. */
|
|
68
|
+
withTx(fn) {
|
|
69
|
+
return runInTransaction(this.db, fn);
|
|
70
|
+
}
|
|
71
|
+
async saveSwap(swap) {
|
|
72
|
+
await this.ensureInit();
|
|
73
|
+
await this.withTx(async () => {
|
|
74
|
+
await this.db.run(
|
|
75
|
+
`INSERT OR REPLACE INTO ${this.swaps} (id, status, created_at, data)
|
|
76
|
+
VALUES (?, ?, ?, ?)`,
|
|
77
|
+
[swap.id, swap.status, swap.createdAt, JSON.stringify(swap)]
|
|
78
|
+
);
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
async getAllSwaps() {
|
|
82
|
+
await this.ensureInit();
|
|
83
|
+
const rows = await this.db.all(`SELECT data FROM ${this.swaps}`);
|
|
84
|
+
return rows.map((r) => JSON.parse(r.data));
|
|
85
|
+
}
|
|
86
|
+
async getScannedTxids() {
|
|
87
|
+
await this.ensureInit();
|
|
88
|
+
const rows = await this.db.all(`SELECT txid FROM ${this.scanned}`);
|
|
89
|
+
return new Set(rows.map((r) => r.txid));
|
|
90
|
+
}
|
|
91
|
+
async markTxidsScanned(txids) {
|
|
92
|
+
await this.ensureInit();
|
|
93
|
+
const all = [...txids];
|
|
94
|
+
if (all.length === 0) return;
|
|
95
|
+
await this.withTx(async () => {
|
|
96
|
+
for (let i = 0; i < all.length; i += INSERT_CHUNK) {
|
|
97
|
+
const chunk = all.slice(i, i + INSERT_CHUNK);
|
|
98
|
+
await this.db.run(
|
|
99
|
+
`INSERT OR IGNORE INTO ${this.scanned} (txid) VALUES ${chunk.map(() => "(?)").join(", ")}`,
|
|
100
|
+
chunk
|
|
101
|
+
);
|
|
102
|
+
}
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
async getCachedMarkets(network, registry) {
|
|
106
|
+
await this.ensureInit();
|
|
107
|
+
const row = await this.db.get(
|
|
108
|
+
`SELECT data FROM ${this.markets} WHERE cache_key = ?`,
|
|
109
|
+
[marketsCacheKey(network, registry)]
|
|
110
|
+
);
|
|
111
|
+
return row ? JSON.parse(row.data) : void 0;
|
|
112
|
+
}
|
|
113
|
+
async saveCachedMarkets(network, registry, entry) {
|
|
114
|
+
await this.ensureInit();
|
|
115
|
+
await this.withTx(async () => {
|
|
116
|
+
await this.db.run(
|
|
117
|
+
`INSERT OR REPLACE INTO ${this.markets} (cache_key, data) VALUES (?, ?)`,
|
|
118
|
+
[marketsCacheKey(network, registry), JSON.stringify(entry)]
|
|
119
|
+
);
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
/** All three tables in one transaction: clearing swaps but keeping scanned
|
|
123
|
+
* txids would leave the restore scan permanently skipping those funding
|
|
124
|
+
* txs, so a partial clear must not be observable. */
|
|
125
|
+
async clear() {
|
|
126
|
+
await this.ensureInit();
|
|
127
|
+
await this.withTx(async () => {
|
|
128
|
+
await this.db.run(`DELETE FROM ${this.swaps}`);
|
|
129
|
+
await this.db.run(`DELETE FROM ${this.scanned}`);
|
|
130
|
+
await this.db.run(`DELETE FROM ${this.markets}`);
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
async [Symbol.asyncDispose]() {
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
export {
|
|
137
|
+
SQLiteAssetSwapRepository
|
|
138
|
+
};
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
import { DiscoveredMarket } from '@arkade-os/solver-discovery';
|
|
2
|
+
import { IWallet, ProvisionedKey, ProvisionedClaimSecret } from '@arkade-os/sdk';
|
|
3
|
+
|
|
4
|
+
type AssetSwapStatus = "pending" | "cancelling" | "fulfilled" | "cancelled" | "recoverable" | "awaiting_fill" | "claimable" | "claimed" | "refunded_l1";
|
|
5
|
+
/** The sentinel asset id for BTC itself, as opposed to a 68-hex asset id.
|
|
6
|
+
* Lives here with the {@link AssetSwap} fields it describes so the market and
|
|
7
|
+
* restore layers share one spelling instead of re-typing the literal. */
|
|
8
|
+
declare const BTC_ASSET_ID = "btc";
|
|
9
|
+
/**
|
|
10
|
+
* The record fields a wallet-provisioned secret becomes — what
|
|
11
|
+
* {@link swapSecretsToRecord} emits, and what every record type carrying swap
|
|
12
|
+
* secrets embeds.
|
|
13
|
+
*
|
|
14
|
+
* A named type rather than four fields restated per record: the mapper and the
|
|
15
|
+
* records it feeds must agree exactly, and a record that silently omits one of
|
|
16
|
+
* these round-trips a swap whose preimage cannot be re-derived. Embedding makes
|
|
17
|
+
* the omission a compile error instead.
|
|
18
|
+
*
|
|
19
|
+
* **Only `preimageHex` is secret.** `signingDescriptor` and `preimageSaltHex`
|
|
20
|
+
* are public derivation inputs — they must survive a field-mapped backend, but
|
|
21
|
+
* they leak nothing without the seed.
|
|
22
|
+
*/
|
|
23
|
+
interface SwapSecretsProjection {
|
|
24
|
+
/**
|
|
25
|
+
* The wallet descriptor this swap's sender key comes from — a fresh HD
|
|
26
|
+
* child, or a static wallet's `tr(pubkey)`. Public — the signer
|
|
27
|
+
* re-derives from the wallet, so the record carries no key material.
|
|
28
|
+
*/
|
|
29
|
+
signingDescriptor?: string;
|
|
30
|
+
/** P, hex, when it cannot be re-derived from the seed at all: the user
|
|
31
|
+
* supplied it, or the signer cannot sign deterministically. The swap's only
|
|
32
|
+
* claim secret when present. */
|
|
33
|
+
preimageHex?: string;
|
|
34
|
+
/**
|
|
35
|
+
* The salt P derives from, hex, on the salted arm — what a static wallet
|
|
36
|
+
* gets instead of storing P. **Public**, and unlike every other field here
|
|
37
|
+
* it is minted per swap: it is what stops one repeating key from handing
|
|
38
|
+
* every swap the same preimage.
|
|
39
|
+
*/
|
|
40
|
+
preimageSaltHex?: string;
|
|
41
|
+
}
|
|
42
|
+
interface AssetSwap extends SwapSecretsProjection {
|
|
43
|
+
/** Funding txid — the swap's identity. */
|
|
44
|
+
id: string;
|
|
45
|
+
/** 'btc' or a 68-hex asset id. */
|
|
46
|
+
fromAsset: string;
|
|
47
|
+
toAsset: string;
|
|
48
|
+
/** Atomic amounts as strings (bigint is not JSON-safe). */
|
|
49
|
+
fromAmount: string;
|
|
50
|
+
/** The covenant wantAmount — a floor, the fill pays >= this. */
|
|
51
|
+
toAmount: string;
|
|
52
|
+
swapAddress: string;
|
|
53
|
+
/** Hex pkScript of the swap contract — the indexer monitoring key. */
|
|
54
|
+
swapPkScript: string;
|
|
55
|
+
/** TLV offer — needed to rebuild the contract for cancel. */
|
|
56
|
+
offerHex: string;
|
|
57
|
+
fundingTxid: string;
|
|
58
|
+
spentTxid?: string;
|
|
59
|
+
status: AssetSwapStatus;
|
|
60
|
+
createdAt: number;
|
|
61
|
+
completedAt?: number;
|
|
62
|
+
/** RFQ pair string, e.g. `arkade:BTC->onchain:BTC`. */
|
|
63
|
+
pair?: string;
|
|
64
|
+
/** `sha256(P)`, hex. Public, and how a restore confirms a candidate
|
|
65
|
+
* derivation is the right one. */
|
|
66
|
+
paymentHash?: string;
|
|
67
|
+
/** The L1 HTLC's pkScript, hex — the chain-watch key. */
|
|
68
|
+
htlcPkScriptHex?: string;
|
|
69
|
+
htlcLocktime?: number;
|
|
70
|
+
/** The L1 funding txid, once observed. */
|
|
71
|
+
l1Txid?: string;
|
|
72
|
+
}
|
|
73
|
+
/** All swaps, newest-first. Insertion order is not chronological — the restore
|
|
74
|
+
* scan rebuilds records in tx-scan order — so sort at read to keep
|
|
75
|
+
* newest-first canonical for every consumer. */
|
|
76
|
+
declare const getAssetSwapsOrThrow: (repository: AssetSwapRepository) => Promise<AssetSwap[]>;
|
|
77
|
+
/** The consumer read: a broken backend reads as no swaps rather than crashing
|
|
78
|
+
* a history view. Mutations must use {@link getAssetSwapsOrThrow} instead —
|
|
79
|
+
* swallowing the read there would let "the backend is gone" masquerade as "no
|
|
80
|
+
* such swap" and skip the write silently. */
|
|
81
|
+
declare const getAssetSwaps: (repository: AssetSwapRepository) => Promise<AssetSwap[]>;
|
|
82
|
+
/** Add a swap; no-op if the id is already stored. Returns the updated list.
|
|
83
|
+
* THROWS on a failed write — nothing irreversible may happen until this record
|
|
84
|
+
* is durable, so the caller must not fund on a failure. */
|
|
85
|
+
declare const addAssetSwap: (repository: AssetSwapRepository, swap: AssetSwap) => Promise<AssetSwap[]>;
|
|
86
|
+
/** Merge changes into a swap by id. Returns the updated list.
|
|
87
|
+
* THROWS on a failed read or write, like {@link addAssetSwap} — use this for a
|
|
88
|
+
* write that gates something irreversible. Transitions written *after* the
|
|
89
|
+
* irreversible act belong on {@link updateAssetSwapBestEffort}. */
|
|
90
|
+
declare const updateAssetSwap: (repository: AssetSwapRepository, id: string, changes: Partial<Omit<AssetSwap, "id">>) => Promise<AssetSwap[]>;
|
|
91
|
+
/**
|
|
92
|
+
* {@link updateAssetSwap} for transitions that follow an irreversible action (a
|
|
93
|
+
* broadcast claim, a spent lockup): failing the caller there would report as
|
|
94
|
+
* failed a swap whose funds already moved, and a stale status is recoverable —
|
|
95
|
+
* crash recovery re-derives the true state from the chain
|
|
96
|
+
* (`classifyOnchainHtlc`).
|
|
97
|
+
*
|
|
98
|
+
* `persisted` is the part that must not be hidden: a caller that notifies on a
|
|
99
|
+
* change, or treats one as terminal, has to know the store did not agree.
|
|
100
|
+
*/
|
|
101
|
+
declare const updateAssetSwapBestEffort: (repository: AssetSwapRepository, id: string, changes: Partial<Omit<AssetSwap, "id">>) => Promise<{
|
|
102
|
+
swaps: AssetSwap[];
|
|
103
|
+
persisted: boolean;
|
|
104
|
+
}>;
|
|
105
|
+
/**
|
|
106
|
+
* The record fields a wallet-provisioned secret becomes.
|
|
107
|
+
*
|
|
108
|
+
* `signingDescriptor` is public and always stored — it is what recovers the
|
|
109
|
+
* signer. Then at most one of: `preimageHex`, when the wallet says it cannot
|
|
110
|
+
* re-derive P and it becomes the swap's only claim secret; or
|
|
111
|
+
* `preimageSaltHex`, the public input a derivable-but-repeating key needs.
|
|
112
|
+
*/
|
|
113
|
+
declare const swapSecretsToRecord: (secrets: ProvisionedKey | ProvisionedClaimSecret) => SwapSecretsProjection & {
|
|
114
|
+
signingDescriptor: string;
|
|
115
|
+
};
|
|
116
|
+
/** Why a wallet cannot produce a swap's preimage. */
|
|
117
|
+
type PreimageBlockedReason =
|
|
118
|
+
/** The record carries no `signingDescriptor`. */
|
|
119
|
+
"no-secrets"
|
|
120
|
+
/** `preimageHex` or `preimageSaltHex` is present but not 32 bytes of hex. */
|
|
121
|
+
| "malformed-record"
|
|
122
|
+
/**
|
|
123
|
+
* Nothing to derive from: a descriptor that repeats across swaps, with
|
|
124
|
+
* neither a stored preimage nor a salt — or one this wallet holds no key
|
|
125
|
+
* for. Merged deliberately: `contractSigner` reports a key it does not
|
|
126
|
+
* hold as a plain `Error` for static wallets and a `ForeignDescriptorError`
|
|
127
|
+
* for HD ones, so splitting the two here would mean matching on message
|
|
128
|
+
* text, which is the thing this type exists to avoid. The `cause` carries
|
|
129
|
+
* whichever it was.
|
|
130
|
+
*/
|
|
131
|
+
| "not-derivable"
|
|
132
|
+
/** Derived, but it does not hash to the record's `paymentHash`. */
|
|
133
|
+
| "hash-mismatch";
|
|
134
|
+
/**
|
|
135
|
+
* The wallet cannot produce this swap's preimage, and which of the four ways
|
|
136
|
+
* is `reason`.
|
|
137
|
+
*
|
|
138
|
+
* Deliberately **not** {@link RefundNotLocallyPossibleError}: that one means
|
|
139
|
+
* "no local refund is possible", and `RfqSwapManager` acts on it by reporting
|
|
140
|
+
* `needs_counterparty`. A claim-path read failure is a different verdict, and
|
|
141
|
+
* borrowing the refund error would have the manager announce one for the
|
|
142
|
+
* other.
|
|
143
|
+
*/
|
|
144
|
+
declare class PreimageNotRecoverableError extends Error {
|
|
145
|
+
readonly reason: PreimageBlockedReason;
|
|
146
|
+
readonly name = "PreimageNotRecoverableError";
|
|
147
|
+
constructor(reason: PreimageBlockedReason, message: string, options?: {
|
|
148
|
+
cause?: unknown;
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* The preimage a swap record claims with — stored, or re-derived from the
|
|
153
|
+
* wallet.
|
|
154
|
+
*
|
|
155
|
+
* The record-shaped inverse of {@link swapSecretsToRecord}, and the one place
|
|
156
|
+
* that knows which of a record's fields `contractPreimage` needs. Wire claim
|
|
157
|
+
* paths here rather than composing it by hand: a caller that forgets to pass
|
|
158
|
+
* `preimageSaltHex` gets a *wrong* preimage from a wallet that can derive,
|
|
159
|
+
* not an error.
|
|
160
|
+
*
|
|
161
|
+
* Verifies the result against `paymentHash` when the record carries one. The
|
|
162
|
+
* salted arm has two inputs that can be wrong — the key and the salt — where
|
|
163
|
+
* the HD arm had one, and a wrong P otherwise surfaces as an opaque script
|
|
164
|
+
* failure at claim time, long after the mistake.
|
|
165
|
+
*
|
|
166
|
+
* Every refusal is a {@link PreimageNotRecoverableError} carrying a `reason`,
|
|
167
|
+
* so a caller can tell "this record predates the descriptor" from "the salt is
|
|
168
|
+
* corrupt" without reading message text.
|
|
169
|
+
*/
|
|
170
|
+
declare const preimageForSwapRecord: (wallet: IWallet, record: SwapSecretsProjection & {
|
|
171
|
+
paymentHash?: string;
|
|
172
|
+
}) => Promise<Uint8Array>;
|
|
173
|
+
|
|
174
|
+
/** A registry discovery result held for reuse. Refetchable — unlike a swap
|
|
175
|
+
* record, losing it costs one network round trip — but it must survive a cold
|
|
176
|
+
* boot: serving it stale is what keeps quoting alive while a registry is down. */
|
|
177
|
+
interface MarketsCacheEntry {
|
|
178
|
+
markets: DiscoveredMarket[];
|
|
179
|
+
fetchedAt: number;
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* Everything the package persists, following the monorepo repository
|
|
183
|
+
* convention (versioned interface, AsyncDisposable, one backend per
|
|
184
|
+
* platform — see the Boltz plugin's SwapRepository). Consumers construct
|
|
185
|
+
* exactly one of these; there is no second storage seam.
|
|
186
|
+
*
|
|
187
|
+
* Durable records (swaps) and rebuildable state (the restore scan's txid
|
|
188
|
+
* cursor, the markets cache) live side by side because they share a
|
|
189
|
+
* lifetime: all three belong to one wallet on one device, and a consumer
|
|
190
|
+
* that wipes one wants all three gone.
|
|
191
|
+
*
|
|
192
|
+
* ponytail: no query filters — every consumer reads all swaps and filters
|
|
193
|
+
* in memory; mirror the Boltz plugin's GetSwapsFilter when a consumer needs
|
|
194
|
+
* subset queries.
|
|
195
|
+
*/
|
|
196
|
+
interface AssetSwapRepository extends AsyncDisposable {
|
|
197
|
+
readonly version: 2;
|
|
198
|
+
/** Insert or replace a swap by id. Store the record whole: `preimageHex`
|
|
199
|
+
* and `preimageSaltHex` both leave the swap unclaimable if a field-mapped
|
|
200
|
+
* backend drops them — the first is the only claim secret of a swap whose
|
|
201
|
+
* signer cannot derive, the second the public input every other static
|
|
202
|
+
* wallet's preimage derives from.
|
|
203
|
+
*
|
|
204
|
+
* Records must be **JSON-safe**: the SQLite and Realm backends serialize
|
|
205
|
+
* the record to JSON, so a `Date` in a consumer-added field comes back a
|
|
206
|
+
* string, a `Set`/`Map` comes back empty, and a `bigint` throws here —
|
|
207
|
+
* none of which happens on IndexedDB's structured clone. `AssetSwap` as
|
|
208
|
+
* declared is JSON-safe; keep added fields that way. */
|
|
209
|
+
saveSwap(swap: AssetSwap): Promise<void>;
|
|
210
|
+
/** All stored swaps, in no particular order — `getAssetSwaps` is the
|
|
211
|
+
* canonical newest-first read. */
|
|
212
|
+
getAllSwaps(): Promise<AssetSwap[]>;
|
|
213
|
+
/** Sent txids already checked for offer packets (see restore.ts). */
|
|
214
|
+
getScannedTxids(): Promise<Set<string>>;
|
|
215
|
+
markTxidsScanned(txids: Iterable<string>): Promise<void>;
|
|
216
|
+
/** Cached registry markets, or undefined on a miss. */
|
|
217
|
+
getCachedMarkets(network: string, registry: string): Promise<MarketsCacheEntry | undefined>;
|
|
218
|
+
saveCachedMarkets(network: string, registry: string, entry: MarketsCacheEntry): Promise<void>;
|
|
219
|
+
clear(): Promise<void>;
|
|
220
|
+
}
|
|
221
|
+
declare class InMemoryAssetSwapRepository implements AssetSwapRepository {
|
|
222
|
+
readonly version: 2;
|
|
223
|
+
private readonly swaps;
|
|
224
|
+
private readonly scanned;
|
|
225
|
+
private readonly markets;
|
|
226
|
+
saveSwap(swap: AssetSwap): Promise<void>;
|
|
227
|
+
getAllSwaps(): Promise<AssetSwap[]>;
|
|
228
|
+
getScannedTxids(): Promise<Set<string>>;
|
|
229
|
+
markTxidsScanned(txids: Iterable<string>): Promise<void>;
|
|
230
|
+
getCachedMarkets(network: string, registry: string): Promise<MarketsCacheEntry | undefined>;
|
|
231
|
+
saveCachedMarkets(network: string, registry: string, entry: MarketsCacheEntry): Promise<void>;
|
|
232
|
+
clear(): Promise<void>;
|
|
233
|
+
[Symbol.asyncDispose](): Promise<void>;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
export { type AssetSwapRepository as A, BTC_ASSET_ID as B, InMemoryAssetSwapRepository as I, type MarketsCacheEntry as M, type PreimageBlockedReason as P, type SwapSecretsProjection as S, type AssetSwap as a, type AssetSwapStatus as b, PreimageNotRecoverableError as c, addAssetSwap as d, getAssetSwapsOrThrow as e, updateAssetSwapBestEffort as f, getAssetSwaps as g, preimageForSwapRecord as p, swapSecretsToRecord as s, updateAssetSwap as u };
|