@totemsdk/omnia-host 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +38 -0
- package/dist/api/jsonrpc.d.ts +33 -0
- package/dist/api/jsonrpc.js +114 -0
- package/dist/api/methods.d.ts +26 -0
- package/dist/api/methods.js +412 -0
- package/dist/chain/totem-node-adapter.d.ts +23 -0
- package/dist/chain/totem-node-adapter.js +78 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +32 -0
- package/dist/config.d.ts +17 -0
- package/dist/config.js +49 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.js +23 -0
- package/dist/lifecycle.d.ts +45 -0
- package/dist/lifecycle.js +141 -0
- package/dist/router/go-routing-provider.d.ts +13 -0
- package/dist/router/go-routing-provider.js +66 -0
- package/dist/router/routing-provider.d.ts +21 -0
- package/dist/router/routing-provider.js +67 -0
- package/dist/stores/analytics.d.ts +36 -0
- package/dist/stores/analytics.js +53 -0
- package/dist/stores/operations.d.ts +25 -0
- package/dist/stores/operations.js +101 -0
- package/dist/stores/sqlite-store.d.ts +21 -0
- package/dist/stores/sqlite-store.js +97 -0
- package/package.json +74 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024-2026 Totem SDK Contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
# @totemsdk/omnia-host
|
|
2
|
+
|
|
3
|
+
The Omnia host daemon will provide durable channel lifecycle, routing, chain
|
|
4
|
+
integration, and control APIs for a Totem node. Phase 1 contains the package
|
|
5
|
+
and lifecycle scaffold; subsystem implementations are added incrementally.
|
|
6
|
+
|
|
7
|
+
## Run
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
OMNIA_CHAIN_RPC_PASSWORD=secret pnpm --filter @totemsdk/omnia-host build
|
|
11
|
+
OMNIA_CHAIN_RPC_PASSWORD=secret pnpm --filter @totemsdk/omnia-host start
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
The daemon configuration is read from environment variables:
|
|
15
|
+
|
|
16
|
+
| Variable | Default | Purpose |
|
|
17
|
+
| --- | --- | --- |
|
|
18
|
+
| `OMNIA_HOST_PORT` | `50052` | Host control and health port |
|
|
19
|
+
| `OMNIA_HOST_DB` | `~/.totem/omnia/omnia.sqlite` | Durable channel database |
|
|
20
|
+
| `OMNIA_CHAIN_RPC` | `http://127.0.0.1:9005` | Totem node RPC endpoint |
|
|
21
|
+
| `OMNIA_CHAIN_RPC_PASSWORD` | unset | Totem node RPC password |
|
|
22
|
+
| `OMNIA_ANALYTICS_DB` | unset | Optional DuckDB analytics path |
|
|
23
|
+
| `OMNIA_RELAY` | native swarm | Optional relay URL |
|
|
24
|
+
| `OMNIA_LOCAL_PUBKEY` | unset | Local Omnia identity |
|
|
25
|
+
| `OMNIA_LOCAL_PARTY_ID` | unset | Local channel party ID required for mutations |
|
|
26
|
+
| `OMNIA_LOCAL_ADDRESS_INDEX` | unset | Local WOTS address index |
|
|
27
|
+
| `OMNIA_LOCAL_SETTLEMENT_ADDRESS` | unset | Default cooperative settlement address |
|
|
28
|
+
|
|
29
|
+
The daemon is intended to run beside `totem-node -mode omnia` or `-mode full`.
|
|
30
|
+
The current implementation includes the swarm lifecycle wiring, SQLite and
|
|
31
|
+
operation-store abstractions, JSON-RPC/WebSocket control API, route provider,
|
|
32
|
+
chain adapter, Edge adapter contract, optional Go-router boundary, and DuckDB
|
|
33
|
+
analytics abstraction. Funding/signing mutations remain capability-gated until
|
|
34
|
+
a signer and WOTS lease provider are supplied.
|
|
35
|
+
|
|
36
|
+
The local test environment may skip SQLite integration tests when the
|
|
37
|
+
`better-sqlite3` native addon has not been built. Install lifecycle scripts in
|
|
38
|
+
CI or on the target platform to execute those tests.
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { AddressInfo } from 'node:net';
|
|
2
|
+
import { type WebSocket } from 'ws';
|
|
3
|
+
export interface JsonRpcRequest {
|
|
4
|
+
jsonrpc?: '2.0';
|
|
5
|
+
id?: string | number | null;
|
|
6
|
+
method: string;
|
|
7
|
+
params?: unknown;
|
|
8
|
+
}
|
|
9
|
+
export interface JsonRpcResponse {
|
|
10
|
+
jsonrpc: '2.0';
|
|
11
|
+
id: string | number | null;
|
|
12
|
+
result?: unknown;
|
|
13
|
+
error?: {
|
|
14
|
+
code: number;
|
|
15
|
+
message: string;
|
|
16
|
+
data?: unknown;
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
export type JsonRpcHandler = (params: unknown) => Promise<unknown> | unknown;
|
|
20
|
+
export interface ControlServerOptions {
|
|
21
|
+
host: string;
|
|
22
|
+
port: number;
|
|
23
|
+
wsPath?: string;
|
|
24
|
+
isReady?: () => boolean;
|
|
25
|
+
methods?: Map<string, JsonRpcHandler>;
|
|
26
|
+
onConnection?: (socket: WebSocket) => void;
|
|
27
|
+
}
|
|
28
|
+
export interface ControlServer {
|
|
29
|
+
listen(): Promise<void>;
|
|
30
|
+
close(): Promise<void>;
|
|
31
|
+
readonly address?: AddressInfo;
|
|
32
|
+
}
|
|
33
|
+
export declare function createControlServer(options: ControlServerOptions): ControlServer;
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.createControlServer = createControlServer;
|
|
7
|
+
const node_http_1 = __importDefault(require("node:http"));
|
|
8
|
+
const ws_1 = require("ws");
|
|
9
|
+
function response(id, result) {
|
|
10
|
+
return { jsonrpc: '2.0', id: id ?? null, result };
|
|
11
|
+
}
|
|
12
|
+
function errorResponse(id, code, message) {
|
|
13
|
+
return { jsonrpc: '2.0', id: id ?? null, error: { code, message } };
|
|
14
|
+
}
|
|
15
|
+
async function dispatch(request, methods) {
|
|
16
|
+
if (request.jsonrpc !== undefined && request.jsonrpc !== '2.0') {
|
|
17
|
+
return errorResponse(request.id, -32600, 'Invalid Request');
|
|
18
|
+
}
|
|
19
|
+
if (!request.method || typeof request.method !== 'string') {
|
|
20
|
+
return errorResponse(request.id, -32600, 'Invalid Request');
|
|
21
|
+
}
|
|
22
|
+
const method = methods.get(request.method);
|
|
23
|
+
if (!method)
|
|
24
|
+
return errorResponse(request.id, -32601, `Method not found: ${request.method}`);
|
|
25
|
+
try {
|
|
26
|
+
return response(request.id, await method(request.params));
|
|
27
|
+
}
|
|
28
|
+
catch (error) {
|
|
29
|
+
console.error('[jsonrpc] handler error:', error instanceof Error ? error.stack ?? error.message : String(error));
|
|
30
|
+
return errorResponse(request.id, -32000, 'Internal error');
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
async function readBody(req) {
|
|
34
|
+
const chunks = [];
|
|
35
|
+
for await (const chunk of req) {
|
|
36
|
+
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
|
37
|
+
if (Buffer.concat(chunks).length > 10 * 1024 * 1024)
|
|
38
|
+
throw new Error('Request body too large');
|
|
39
|
+
}
|
|
40
|
+
return Buffer.concat(chunks).toString('utf8');
|
|
41
|
+
}
|
|
42
|
+
function sendJson(res, status, body) {
|
|
43
|
+
const payload = JSON.stringify(body);
|
|
44
|
+
res.writeHead(status, { 'content-type': 'application/json', 'content-length': Buffer.byteLength(payload) });
|
|
45
|
+
res.end(payload);
|
|
46
|
+
}
|
|
47
|
+
function createControlServer(options) {
|
|
48
|
+
const methods = options.methods ?? new Map();
|
|
49
|
+
const wsPath = options.wsPath ?? '/rpc';
|
|
50
|
+
const server = node_http_1.default.createServer(async (req, res) => {
|
|
51
|
+
if (req.method === 'GET' && req.url === '/healthz') {
|
|
52
|
+
sendJson(res, 200, { ok: true });
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
if (req.method === 'GET' && req.url === '/readyz') {
|
|
56
|
+
const ready = options.isReady?.() ?? false;
|
|
57
|
+
sendJson(res, ready ? 200 : 503, { ok: ready });
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
if (req.method !== 'POST' || req.url !== wsPath) {
|
|
61
|
+
sendJson(res, 404, { error: 'Not found' });
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
try {
|
|
65
|
+
const request = JSON.parse(await readBody(req));
|
|
66
|
+
sendJson(res, 200, await dispatch(request, methods));
|
|
67
|
+
}
|
|
68
|
+
catch (error) {
|
|
69
|
+
console.error('[jsonrpc] parse error:', error instanceof Error ? error.stack ?? error.message : String(error));
|
|
70
|
+
sendJson(res, 400, errorResponse(null, -32700, 'Invalid JSON RPC request'));
|
|
71
|
+
}
|
|
72
|
+
});
|
|
73
|
+
const webSockets = new ws_1.WebSocketServer({ noServer: true });
|
|
74
|
+
server.on('upgrade', (req, socket, head) => {
|
|
75
|
+
if (req.url !== wsPath) {
|
|
76
|
+
socket.destroy();
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
webSockets.handleUpgrade(req, socket, head, (ws) => {
|
|
80
|
+
webSockets.emit('connection', ws, req);
|
|
81
|
+
});
|
|
82
|
+
});
|
|
83
|
+
webSockets.on('connection', (socket) => {
|
|
84
|
+
options.onConnection?.(socket);
|
|
85
|
+
socket.on('message', async (data) => {
|
|
86
|
+
try {
|
|
87
|
+
const request = JSON.parse(data.toString());
|
|
88
|
+
socket.send(JSON.stringify(await dispatch(request, methods)));
|
|
89
|
+
}
|
|
90
|
+
catch (error) {
|
|
91
|
+
console.error('[jsonrpc] ws parse error:', error instanceof Error ? error.stack ?? error.message : String(error));
|
|
92
|
+
socket.send(JSON.stringify(errorResponse(null, -32700, 'Invalid JSON RPC request')));
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
});
|
|
96
|
+
let address;
|
|
97
|
+
return {
|
|
98
|
+
get address() { return address; },
|
|
99
|
+
async listen() {
|
|
100
|
+
await new Promise((resolve, reject) => {
|
|
101
|
+
server.once('error', reject);
|
|
102
|
+
server.listen(options.port, options.host, () => {
|
|
103
|
+
server.off('error', reject);
|
|
104
|
+
address = server.address();
|
|
105
|
+
resolve();
|
|
106
|
+
});
|
|
107
|
+
});
|
|
108
|
+
},
|
|
109
|
+
async close() {
|
|
110
|
+
webSockets.close();
|
|
111
|
+
await new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
|
|
112
|
+
},
|
|
113
|
+
};
|
|
114
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { ChannelParticipant, ChannelSigner, OmniaChannel, OmniaSwarm } from '@totemsdk/omnia';
|
|
2
|
+
import type { ChainStateProvider } from '@totemsdk/chain-provider';
|
|
3
|
+
import type { WotsLeaseProvider } from '@totemsdk/wots-lease';
|
|
4
|
+
import { type ChannelFactory, type WotsLeaseBundle } from '@totemsdk/omnia-factory';
|
|
5
|
+
import { type SpliceAcceptance, type SpliceLeaseProvider, type SpliceProposal } from '@totemsdk/omnia-splice';
|
|
6
|
+
import type { JsonRpcHandler } from './jsonrpc.js';
|
|
7
|
+
import type { RoutingProvider } from '../router/routing-provider.js';
|
|
8
|
+
import type { OperationStore } from '../stores/operations.js';
|
|
9
|
+
export type OperationStoreLike = Pick<OperationStore, 'get' | 'create' | 'transition' | 'listByStatus'>;
|
|
10
|
+
export interface HostApiContext {
|
|
11
|
+
channels: Map<string, OmniaChannel>;
|
|
12
|
+
routing: RoutingProvider;
|
|
13
|
+
refreshRouting?: () => void;
|
|
14
|
+
operations?: OperationStoreLike;
|
|
15
|
+
signer?: ChannelSigner;
|
|
16
|
+
leaseProvider?: WotsLeaseProvider;
|
|
17
|
+
chainProvider?: ChainStateProvider;
|
|
18
|
+
swarm?: OmniaSwarm;
|
|
19
|
+
localParticipant?: ChannelParticipant;
|
|
20
|
+
factories?: Map<string, ChannelFactory>;
|
|
21
|
+
factoryBundles?: Record<string, WotsLeaseBundle>;
|
|
22
|
+
spliceProposals?: Map<string, SpliceProposal>;
|
|
23
|
+
spliceAcceptances?: Map<string, SpliceAcceptance>;
|
|
24
|
+
spliceLeaseProvider?: SpliceLeaseProvider;
|
|
25
|
+
}
|
|
26
|
+
export declare function createHostMethods(context: HostApiContext): Map<string, JsonRpcHandler>;
|
|
@@ -0,0 +1,412 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createHostMethods = createHostMethods;
|
|
4
|
+
const omnia_1 = require("@totemsdk/omnia");
|
|
5
|
+
const omnia_factory_1 = require("@totemsdk/omnia-factory");
|
|
6
|
+
const omnia_splice_1 = require("@totemsdk/omnia-splice");
|
|
7
|
+
function channelSummary(channel) {
|
|
8
|
+
const parties = channel.parties.map((party) => party.partyId);
|
|
9
|
+
return {
|
|
10
|
+
channelId: channel.channelId,
|
|
11
|
+
status: channel.status,
|
|
12
|
+
tokenId: channel.tokenId,
|
|
13
|
+
totalValue: channel.totalValue.toString(),
|
|
14
|
+
localBalance: (channel.balances[parties[0]] ?? 0n).toString(),
|
|
15
|
+
remoteBalance: (channel.balances[parties[1]] ?? 0n).toString(),
|
|
16
|
+
currentSequence: channel.currentSequence,
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
function paramsObject(params) {
|
|
20
|
+
if (!params || typeof params !== 'object' || Array.isArray(params))
|
|
21
|
+
return {};
|
|
22
|
+
return params;
|
|
23
|
+
}
|
|
24
|
+
function requiredString(params, key) {
|
|
25
|
+
const value = params[key];
|
|
26
|
+
if (typeof value !== 'string' || value.length === 0)
|
|
27
|
+
throw new Error(`${key} is required`);
|
|
28
|
+
return value;
|
|
29
|
+
}
|
|
30
|
+
function requiredBigInt(params, key) {
|
|
31
|
+
const value = requiredString(params, key);
|
|
32
|
+
try {
|
|
33
|
+
return BigInt(value);
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
throw new Error(`${key} must be an integer string`);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
function operationId(params) {
|
|
40
|
+
return requiredString(params, 'operationId');
|
|
41
|
+
}
|
|
42
|
+
function bigintRecord(params, key) {
|
|
43
|
+
const value = params[key];
|
|
44
|
+
if (value === undefined)
|
|
45
|
+
return undefined;
|
|
46
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
47
|
+
throw new Error(`${key} must be an object`);
|
|
48
|
+
return Object.fromEntries(Object.entries(value).map(([partyId, balance]) => [
|
|
49
|
+
partyId,
|
|
50
|
+
BigInt(String(balance)),
|
|
51
|
+
]));
|
|
52
|
+
}
|
|
53
|
+
function optionalStringRecord(params, key) {
|
|
54
|
+
const value = params[key];
|
|
55
|
+
if (value === undefined)
|
|
56
|
+
return undefined;
|
|
57
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
58
|
+
throw new Error(`${key} must be an object`);
|
|
59
|
+
return Object.fromEntries(Object.entries(value).map(([name, nested]) => {
|
|
60
|
+
if (typeof nested !== 'string')
|
|
61
|
+
throw new Error(`${key}.${name} must be a string`);
|
|
62
|
+
return [name, nested];
|
|
63
|
+
}));
|
|
64
|
+
}
|
|
65
|
+
function optionalTransitionInputs(params) {
|
|
66
|
+
const value = params.inputs;
|
|
67
|
+
if (value === undefined)
|
|
68
|
+
return undefined;
|
|
69
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
70
|
+
throw new Error('inputs must be an object');
|
|
71
|
+
return Object.fromEntries(Object.entries(value).map(([name, nested]) => {
|
|
72
|
+
if (typeof nested === 'string' || typeof nested === 'boolean')
|
|
73
|
+
return [name, nested];
|
|
74
|
+
if (typeof nested === 'number' && Number.isSafeInteger(nested))
|
|
75
|
+
return [name, BigInt(nested)];
|
|
76
|
+
throw new Error(`inputs.${name} must be a string, boolean, or safe integer`);
|
|
77
|
+
}));
|
|
78
|
+
}
|
|
79
|
+
function balancesJson(channel) {
|
|
80
|
+
return Object.fromEntries(Object.entries(channel.balances).map(([partyId, balance]) => [partyId, balance.toString()]));
|
|
81
|
+
}
|
|
82
|
+
async function withOperation(context, params, run) {
|
|
83
|
+
if (!context.operations)
|
|
84
|
+
throw new Error('Operation store is not configured');
|
|
85
|
+
const id = operationId(params);
|
|
86
|
+
const existing = context.operations.get(id);
|
|
87
|
+
const verifier = context.operations.verifyRequest;
|
|
88
|
+
if (existing && verifier && !verifier(id, params)) {
|
|
89
|
+
throw new Error(`Operation ${id} request does not match the original request`);
|
|
90
|
+
}
|
|
91
|
+
if (existing?.status === 'committed')
|
|
92
|
+
return existing.result;
|
|
93
|
+
if (existing && !['pending', 'failed'].includes(existing.status)) {
|
|
94
|
+
throw new Error(`Operation ${id} is already ${existing.status}`);
|
|
95
|
+
}
|
|
96
|
+
if (!existing)
|
|
97
|
+
context.operations.create(id, params);
|
|
98
|
+
context.operations.transition(id, existing?.status === 'failed' ? 'failed' : 'pending', 'executing');
|
|
99
|
+
try {
|
|
100
|
+
const result = await run();
|
|
101
|
+
context.operations.transition(id, 'executing', 'committed', { result });
|
|
102
|
+
return result;
|
|
103
|
+
}
|
|
104
|
+
catch (error) {
|
|
105
|
+
context.operations.transition(id, 'executing', 'failed', { error: error instanceof Error ? error.message : String(error) });
|
|
106
|
+
throw error;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
function requireMutationContext(context) {
|
|
110
|
+
if (!context.signer || !context.leaseProvider || !context.chainProvider || !context.localParticipant) {
|
|
111
|
+
throw new Error('Omnia mutations require signer, WOTS lease provider, chain provider, and local participant configuration');
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
async function persistProgramUpdate(context, channelId, run) {
|
|
115
|
+
const channel = context.channels.get(channelId);
|
|
116
|
+
if (!channel)
|
|
117
|
+
throw new Error(`Channel ${channelId} not found`);
|
|
118
|
+
const result = await run(channel);
|
|
119
|
+
if (result.error)
|
|
120
|
+
throw new Error(result.error);
|
|
121
|
+
context.channels.set(channelId, result.channel);
|
|
122
|
+
const remoteParty = channel.parties.find((party) => party.partyId !== context.localParticipant.partyId);
|
|
123
|
+
if (context.swarm && remoteParty) {
|
|
124
|
+
const peer = await context.swarm.connectToPeer(remoteParty.publicKeyDigest, channelId);
|
|
125
|
+
await peer.sendMessage({ type: 'STATE_UPDATE', channelId, nonce: Date.now(), payload: result.signedState });
|
|
126
|
+
}
|
|
127
|
+
return {
|
|
128
|
+
success: true,
|
|
129
|
+
channelId,
|
|
130
|
+
sequence: result.channel.currentSequence,
|
|
131
|
+
balances: balancesJson(result.channel),
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
function createHostMethods(context) {
|
|
135
|
+
const methods = new Map();
|
|
136
|
+
const register = (name, handler, alias) => {
|
|
137
|
+
methods.set(name, handler);
|
|
138
|
+
methods.set(alias, handler);
|
|
139
|
+
};
|
|
140
|
+
const getChannels = (raw) => {
|
|
141
|
+
const params = paramsObject(raw);
|
|
142
|
+
const tokenId = typeof params.tokenId === 'string' ? params.tokenId : undefined;
|
|
143
|
+
const status = typeof params.status === 'string' ? params.status : undefined;
|
|
144
|
+
const channels = Array.from(context.channels.values())
|
|
145
|
+
.filter((channel) => !tokenId || channel.tokenId === tokenId)
|
|
146
|
+
.filter((channel) => !status || channel.status === status)
|
|
147
|
+
.map(channelSummary);
|
|
148
|
+
return { channels };
|
|
149
|
+
};
|
|
150
|
+
register('totem_omniaGetChannels', getChannels, 'omnia/getChannels');
|
|
151
|
+
const getRoute = async (raw) => {
|
|
152
|
+
context.refreshRouting?.();
|
|
153
|
+
const params = paramsObject(raw);
|
|
154
|
+
const route = await context.routing.getRoute({
|
|
155
|
+
from: requiredString(params, 'fromPartyId'),
|
|
156
|
+
to: requiredString(params, 'toPartyId'),
|
|
157
|
+
amount: requiredBigInt(params, 'amount'),
|
|
158
|
+
tokenId: requiredString(params, 'tokenId'),
|
|
159
|
+
targetTokenId: typeof params.targetTokenId === 'string' ? params.targetTokenId : undefined,
|
|
160
|
+
maxHops: typeof params.maxHops === 'number' ? params.maxHops : undefined,
|
|
161
|
+
});
|
|
162
|
+
if (!route)
|
|
163
|
+
return { success: false, error: 'No route found', errorCode: 'ROUTE_NOT_FOUND' };
|
|
164
|
+
return {
|
|
165
|
+
success: true,
|
|
166
|
+
route: {
|
|
167
|
+
...route,
|
|
168
|
+
totalFees: route.totalFees.toString(),
|
|
169
|
+
hops: route.hops.map((hop) => ({
|
|
170
|
+
...hop,
|
|
171
|
+
amount: hop.amount.toString(),
|
|
172
|
+
...('isSwap' in hop && hop.isSwap ? {
|
|
173
|
+
amountIn: hop.amountIn.toString(),
|
|
174
|
+
amountOut: hop.amountOut.toString(),
|
|
175
|
+
} : {}),
|
|
176
|
+
})),
|
|
177
|
+
},
|
|
178
|
+
};
|
|
179
|
+
};
|
|
180
|
+
register('totem_omniaGetRoute', getRoute, 'omnia/getRoute');
|
|
181
|
+
const getSwapRate = () => ({ success: true, announcements: [] });
|
|
182
|
+
register('totem_omniaGetSwapRate', getSwapRate, 'omnia/getSwapRate');
|
|
183
|
+
const openChannel = async (raw) => {
|
|
184
|
+
const params = paramsObject(raw);
|
|
185
|
+
requireMutationContext(context);
|
|
186
|
+
const remotePartyId = requiredString(params, 'remotePartyId');
|
|
187
|
+
const remotePublicKeyDigest = requiredString(params, 'remotePublicKeyDigest');
|
|
188
|
+
const remote = {
|
|
189
|
+
partyId: remotePartyId,
|
|
190
|
+
publicKeyDigest: remotePublicKeyDigest,
|
|
191
|
+
addressIndex: typeof params.remoteAddressIndex === 'number' ? params.remoteAddressIndex : 0,
|
|
192
|
+
settlementAddress: typeof params.remoteSettlementAddress === 'string' ? params.remoteSettlementAddress : undefined,
|
|
193
|
+
};
|
|
194
|
+
const result = await withOperation(context, params, async () => {
|
|
195
|
+
const createParams = {
|
|
196
|
+
localParty: context.localParticipant,
|
|
197
|
+
remoteParty: remote,
|
|
198
|
+
localAmount: requiredBigInt(params, 'localAmount'),
|
|
199
|
+
remoteAmount: requiredBigInt(params, 'remoteAmount'),
|
|
200
|
+
tokenId: typeof params.tokenId === 'string' ? params.tokenId : undefined,
|
|
201
|
+
fundingCoinId: requiredString(params, 'fundingCoinId'),
|
|
202
|
+
fundingWitnessBytes: Buffer.from(requiredString(params, 'fundingWitnessHex').replace(/^0x/i, ''), 'hex'),
|
|
203
|
+
};
|
|
204
|
+
const created = await (0, omnia_1.createChannel)(createParams, context.chainProvider);
|
|
205
|
+
context.channels.set(created.channel.channelId, {
|
|
206
|
+
...created.channel,
|
|
207
|
+
localSigner: context.signer,
|
|
208
|
+
});
|
|
209
|
+
if (context.swarm) {
|
|
210
|
+
const peer = await context.swarm.connectToPeer(remote.publicKeyDigest, created.channel.channelId);
|
|
211
|
+
await peer.sendMessage({ type: 'CHANNEL_PROPOSAL', channelId: created.channel.channelId, nonce: Date.now(), payload: created.proposal });
|
|
212
|
+
}
|
|
213
|
+
return { success: true, channelId: created.channel.channelId, fundingTxId: created.channel.fundingTxId };
|
|
214
|
+
});
|
|
215
|
+
return result;
|
|
216
|
+
};
|
|
217
|
+
register('totem_omniaOpenChannel', openChannel, 'omnia/openChannel');
|
|
218
|
+
const pay = async (raw) => {
|
|
219
|
+
const params = paramsObject(raw);
|
|
220
|
+
requireMutationContext(context);
|
|
221
|
+
const channelId = requiredString(params, 'channelId');
|
|
222
|
+
const amount = requiredBigInt(params, 'amount');
|
|
223
|
+
return withOperation(context, params, async () => {
|
|
224
|
+
const channel = context.channels.get(channelId);
|
|
225
|
+
if (!channel)
|
|
226
|
+
throw new Error(`Channel ${channelId} not found`);
|
|
227
|
+
const localPartyId = context.localParticipant.partyId;
|
|
228
|
+
const remotePartyId = channel.parties.find((party) => party.partyId !== localPartyId)?.partyId;
|
|
229
|
+
if (!remotePartyId)
|
|
230
|
+
throw new Error('Channel counterparty not found');
|
|
231
|
+
if (amount <= 0n || (channel.balances[localPartyId] ?? 0n) < amount)
|
|
232
|
+
throw new Error('Insufficient channel balance');
|
|
233
|
+
const result = await (0, omnia_1.updateState)(channel, {
|
|
234
|
+
newBalances: {
|
|
235
|
+
...channel.balances,
|
|
236
|
+
[localPartyId]: (channel.balances[localPartyId] ?? 0n) - amount,
|
|
237
|
+
[remotePartyId]: (channel.balances[remotePartyId] ?? 0n) + amount,
|
|
238
|
+
},
|
|
239
|
+
}, context.leaseProvider, context.signer);
|
|
240
|
+
if (result.error)
|
|
241
|
+
throw new Error(result.error);
|
|
242
|
+
context.channels.set(channelId, result.channel);
|
|
243
|
+
const peer = context.swarm ? await context.swarm.connectToPeer(channel.parties.find((party) => party.partyId === remotePartyId).publicKeyDigest, channelId) : undefined;
|
|
244
|
+
if (peer)
|
|
245
|
+
await peer.sendMessage({ type: 'STATE_UPDATE', channelId, nonce: Date.now(), payload: result.signedState });
|
|
246
|
+
return { success: true, channelId, sequence: result.channel.currentSequence, localBalance: result.channel.balances[localPartyId].toString(), remoteBalance: result.channel.balances[remotePartyId].toString() };
|
|
247
|
+
});
|
|
248
|
+
};
|
|
249
|
+
register('totem_omniaPay', pay, 'omnia/pay');
|
|
250
|
+
const programTransition = async (raw) => {
|
|
251
|
+
const params = paramsObject(raw);
|
|
252
|
+
requireMutationContext(context);
|
|
253
|
+
const channelId = requiredString(params, 'channelId');
|
|
254
|
+
const transition = {
|
|
255
|
+
action: requiredString(params, 'action'),
|
|
256
|
+
inputs: optionalTransitionInputs(params),
|
|
257
|
+
witness: optionalStringRecord(params, 'witness'),
|
|
258
|
+
metadata: optionalStringRecord(params, 'metadata'),
|
|
259
|
+
};
|
|
260
|
+
const balances = bigintRecord(params, 'balances');
|
|
261
|
+
return withOperation(context, params, async () => persistProgramUpdate(context, channelId, (channel) => (0, omnia_1.applyProgramTransition)(channel, { transition, balances }, context.leaseProvider, context.signer)));
|
|
262
|
+
};
|
|
263
|
+
register('totem_omniaApplyProgramTransition', programTransition, 'omnia/applyProgramTransition');
|
|
264
|
+
const counterTransition = (action) => async (raw) => {
|
|
265
|
+
const params = paramsObject(raw);
|
|
266
|
+
requireMutationContext(context);
|
|
267
|
+
const channelId = requiredString(params, 'channelId');
|
|
268
|
+
return withOperation(context, params, async () => persistProgramUpdate(context, channelId, (channel) => {
|
|
269
|
+
if (action === 'increment')
|
|
270
|
+
return (0, omnia_1.incrementCounter)(channel, requiredBigInt(params, 'by'), context.leaseProvider, context.signer);
|
|
271
|
+
if (action === 'decrement')
|
|
272
|
+
return (0, omnia_1.decrementCounter)(channel, requiredBigInt(params, 'by'), context.leaseProvider, context.signer);
|
|
273
|
+
return (0, omnia_1.setCounter)(channel, requiredBigInt(params, 'value'), context.leaseProvider, context.signer);
|
|
274
|
+
}));
|
|
275
|
+
};
|
|
276
|
+
register('totem_omniaIncrementCounter', counterTransition('increment'), 'omnia/incrementCounter');
|
|
277
|
+
register('totem_omniaDecrementCounter', counterTransition('decrement'), 'omnia/decrementCounter');
|
|
278
|
+
register('totem_omniaSetCounter', counterTransition('set'), 'omnia/setCounter');
|
|
279
|
+
const meterReading = async (raw) => {
|
|
280
|
+
const params = paramsObject(raw);
|
|
281
|
+
requireMutationContext(context);
|
|
282
|
+
const channelId = requiredString(params, 'channelId');
|
|
283
|
+
return withOperation(context, params, async () => persistProgramUpdate(context, channelId, (channel) => (0, omnia_1.recordMeterReading)(channel, requiredBigInt(params, 'reading'), requiredBigInt(params, 'unitPrice'), context.leaseProvider, context.signer)));
|
|
284
|
+
};
|
|
285
|
+
register('totem_omniaRecordMeterReading', meterReading, 'omnia/recordMeterReading');
|
|
286
|
+
const settle = async (raw) => {
|
|
287
|
+
const params = paramsObject(raw);
|
|
288
|
+
requireMutationContext(context);
|
|
289
|
+
const channelId = requiredString(params, 'channelId');
|
|
290
|
+
return withOperation(context, params, async () => {
|
|
291
|
+
const channel = context.channels.get(channelId);
|
|
292
|
+
if (!channel)
|
|
293
|
+
throw new Error(`Channel ${channelId} not found`);
|
|
294
|
+
const closing = (0, omnia_1.markChannelClosing)(channel, 'mutual');
|
|
295
|
+
const settlement = await (0, omnia_1.proposeSettlement)(closing, context.leaseProvider, {
|
|
296
|
+
signer: context.signer,
|
|
297
|
+
chainProvider: context.chainProvider,
|
|
298
|
+
partyAddresses: Object.fromEntries(closing.parties.map((party) => [party.partyId, party.settlementAddress ?? party.publicKeyDigest])),
|
|
299
|
+
});
|
|
300
|
+
context.channels.set(channelId, (0, omnia_1.markChannelClosed)(closing));
|
|
301
|
+
return { success: true, channelId, settlementTxId: settlement.settlementPayload.txpowId, finalBalances: Object.fromEntries(Object.entries(settlement.settlementPayload.balances).map(([key, value]) => [key, value.toString()])) };
|
|
302
|
+
});
|
|
303
|
+
};
|
|
304
|
+
register('totem_omniaSettle', settle, 'omnia/settle');
|
|
305
|
+
const closeChannel = async (raw) => {
|
|
306
|
+
const params = paramsObject(raw);
|
|
307
|
+
const channelId = requiredString(params, 'channelId');
|
|
308
|
+
return withOperation(context, params, async () => {
|
|
309
|
+
const channel = context.channels.get(channelId);
|
|
310
|
+
if (!channel)
|
|
311
|
+
throw new Error(`Channel ${channelId} not found`);
|
|
312
|
+
context.channels.set(channelId, (0, omnia_1.markChannelClosed)(channel));
|
|
313
|
+
return { success: true, channelId };
|
|
314
|
+
});
|
|
315
|
+
};
|
|
316
|
+
register('totem_omniaCloseChannel', closeChannel, 'omnia/closeChannel');
|
|
317
|
+
const createFactoryMethod = async (raw) => {
|
|
318
|
+
const params = paramsObject(raw);
|
|
319
|
+
if (!context.factories || !context.factoryBundles || !context.chainProvider)
|
|
320
|
+
throw new Error('Factory manager is not configured');
|
|
321
|
+
const participants = params.participants;
|
|
322
|
+
if (!Array.isArray(participants) || participants.length < 2)
|
|
323
|
+
throw new Error('participants must contain at least two factory participants');
|
|
324
|
+
const parsed = participants.map((value) => {
|
|
325
|
+
if (!value || typeof value !== 'object')
|
|
326
|
+
throw new Error('Invalid factory participant');
|
|
327
|
+
const item = value;
|
|
328
|
+
return {
|
|
329
|
+
partyId: requiredString(item, 'partyId'),
|
|
330
|
+
publicKeyDigest: requiredString(item, 'publicKeyDigest'),
|
|
331
|
+
addressIndex: Number(item.addressIndex ?? 0),
|
|
332
|
+
contributionAmount: BigInt(requiredString(item, 'contributionAmount')),
|
|
333
|
+
fundingCoinId: typeof item.fundingCoinId === 'string' ? item.fundingCoinId : undefined,
|
|
334
|
+
settlementAddress: typeof item.settlementAddress === 'string' ? item.settlementAddress : undefined,
|
|
335
|
+
};
|
|
336
|
+
});
|
|
337
|
+
const tokenId = typeof params.tokenId === 'string' ? params.tokenId : '0x00';
|
|
338
|
+
const bundles = context.factoryBundles;
|
|
339
|
+
const proposer = parsed.find((participant) => bundles[participant.partyId]);
|
|
340
|
+
if (!proposer)
|
|
341
|
+
throw new Error('No local factory lease bundle matches a participant');
|
|
342
|
+
return withOperation(context, params, async () => {
|
|
343
|
+
const factory = await (0, omnia_factory_1.createFactory)(parsed, tokenId, bundles[proposer.partyId], context.chainProvider);
|
|
344
|
+
context.factories.set(factory.factoryId, factory);
|
|
345
|
+
return { success: true, factoryId: factory.factoryId, fundingTxId: factory.fundingTxId };
|
|
346
|
+
});
|
|
347
|
+
};
|
|
348
|
+
register('totem_omniaCreateFactory', createFactoryMethod, 'omnia/createFactory');
|
|
349
|
+
const openVirtual = async (raw) => {
|
|
350
|
+
const params = paramsObject(raw);
|
|
351
|
+
if (!context.factories || !context.factoryBundles)
|
|
352
|
+
throw new Error('Factory manager is not configured');
|
|
353
|
+
const factoryId = requiredString(params, 'factoryId');
|
|
354
|
+
const factory = context.factories.get(factoryId);
|
|
355
|
+
if (!factory)
|
|
356
|
+
throw new Error(`Factory ${factoryId} not found`);
|
|
357
|
+
const parties = params.partyIds;
|
|
358
|
+
if (!Array.isArray(parties) || parties.length !== 2 || !parties.every((value) => typeof value === 'string'))
|
|
359
|
+
throw new Error('partyIds must contain two party IDs');
|
|
360
|
+
const amounts = params.amounts;
|
|
361
|
+
if (!amounts || typeof amounts !== 'object')
|
|
362
|
+
throw new Error('amounts is required');
|
|
363
|
+
const parsedAmounts = Object.fromEntries(Object.entries(amounts).map(([key, value]) => [key, BigInt(String(value))]));
|
|
364
|
+
return withOperation(context, params, async () => {
|
|
365
|
+
const result = await (0, omnia_factory_1.openVirtualChannel)(factory, parties, parsedAmounts, context.factoryBundles);
|
|
366
|
+
context.factories.set(factoryId, result.factory);
|
|
367
|
+
context.channels.set(result.channel.channelId, result.channel);
|
|
368
|
+
return { success: true, channelId: result.channel.channelId, factoryId };
|
|
369
|
+
});
|
|
370
|
+
};
|
|
371
|
+
register('totem_omniaOpenVirtualChannel', openVirtual, 'omnia/openVirtualChannel');
|
|
372
|
+
const closeFactoryMethod = async (raw) => {
|
|
373
|
+
const params = paramsObject(raw);
|
|
374
|
+
if (!context.factories || !context.factoryBundles || !context.chainProvider)
|
|
375
|
+
throw new Error('Factory manager is not configured');
|
|
376
|
+
const factoryId = requiredString(params, 'factoryId');
|
|
377
|
+
const factory = context.factories.get(factoryId);
|
|
378
|
+
if (!factory)
|
|
379
|
+
throw new Error(`Factory ${factoryId} not found`);
|
|
380
|
+
return withOperation(context, params, async () => {
|
|
381
|
+
const payload = await (0, omnia_factory_1.closeFactory)(factory, context.factoryBundles, context.chainProvider);
|
|
382
|
+
context.factories.set(factoryId, { ...factory, status: 'closed' });
|
|
383
|
+
return { success: true, factoryId, settlementTxId: payload.txpowId, finalAllocations: Object.fromEntries(Object.entries(payload.finalAllocations).map(([key, value]) => [key, value.toString()])) };
|
|
384
|
+
});
|
|
385
|
+
};
|
|
386
|
+
register('totem_omniaCloseFactory', closeFactoryMethod, 'omnia/closeFactory');
|
|
387
|
+
const splice = (type) => async (raw) => {
|
|
388
|
+
const params = paramsObject(raw);
|
|
389
|
+
if (!context.spliceLeaseProvider || !context.spliceProposals)
|
|
390
|
+
throw new Error('Splice manager is not configured');
|
|
391
|
+
const channelId = requiredString(params, 'channelId');
|
|
392
|
+
const channel = context.channels.get(channelId);
|
|
393
|
+
if (!channel)
|
|
394
|
+
throw new Error(`Channel ${channelId} not found`);
|
|
395
|
+
return withOperation(context, params, async () => {
|
|
396
|
+
const quiesced = await (0, omnia_splice_1.quiesceChannel)(channel, context.spliceLeaseProvider);
|
|
397
|
+
const proposal = type === 'in'
|
|
398
|
+
? await (0, omnia_splice_1.proposeSpliceIn)(quiesced, requiredString(params, 'additionalCoinId'), requiredBigInt(params, 'additionalAmount'), context.spliceLeaseProvider, params.newBalances)
|
|
399
|
+
: await (0, omnia_splice_1.proposeSpliceOut)(quiesced, requiredBigInt(params, 'withdrawAmount'), requiredString(params, 'withdrawAddress'), context.spliceLeaseProvider, params.newBalances);
|
|
400
|
+
context.spliceProposals.set(proposal.spliceId, proposal);
|
|
401
|
+
context.channels.set(channelId, quiesced);
|
|
402
|
+
return { success: true, channelId, spliceId: proposal.spliceId, updatedChannelState: proposal.spliceTxHex };
|
|
403
|
+
});
|
|
404
|
+
};
|
|
405
|
+
register('totem_omniaSpliceIn', splice('in'), 'omnia/spliceIn');
|
|
406
|
+
register('totem_omniaSpliceOut', splice('out'), 'omnia/spliceOut');
|
|
407
|
+
const unsupported = () => {
|
|
408
|
+
throw new Error('This operation requires a counterparty proposal/acceptance round');
|
|
409
|
+
};
|
|
410
|
+
register('totem_omniaPayMultiHop', unsupported, 'omnia/payMultiHop');
|
|
411
|
+
return methods;
|
|
412
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { ChainStateProvider, ChainTip } from '@totemsdk/chain-provider';
|
|
2
|
+
import { type MinimaRpcClient } from '@totemsdk/minima-rpc';
|
|
3
|
+
export interface TotemNodeAdapterOptions {
|
|
4
|
+
host: string;
|
|
5
|
+
port: number;
|
|
6
|
+
password?: string;
|
|
7
|
+
ssl?: boolean;
|
|
8
|
+
pollIntervalMs?: number;
|
|
9
|
+
provider?: ChainStateProvider;
|
|
10
|
+
client?: MinimaRpcClient;
|
|
11
|
+
}
|
|
12
|
+
export interface ConfirmationOptions {
|
|
13
|
+
timeoutMs?: number;
|
|
14
|
+
pollIntervalMs?: number;
|
|
15
|
+
minConfirmations?: number;
|
|
16
|
+
}
|
|
17
|
+
export interface TotemNodeAdapter extends ChainStateProvider {
|
|
18
|
+
getMode(): Promise<string | undefined>;
|
|
19
|
+
waitForConfirmation(coinId: string, options?: ConfirmationOptions): Promise<void>;
|
|
20
|
+
subscribe(listener: (tip: ChainTip) => void): () => void;
|
|
21
|
+
close(): void;
|
|
22
|
+
}
|
|
23
|
+
export declare function createTotemNodeAdapter(options: TotemNodeAdapterOptions): TotemNodeAdapter;
|