@totemsdk/chain-provider 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,63 @@
1
+ /**
2
+ * @module @totemsdk/chain-provider/resolve
3
+ *
4
+ * User-selectable chain access (RFC-013 §7). Axia remains the default relay;
5
+ * self-hosted mode resolves reads/broadcast through a user's own Minima node,
6
+ * with an optional composite (node-first, Axia-fallback) mode.
7
+ *
8
+ * The resolver is wallet-agnostic: it takes the persisted
9
+ * {@link ChainProviderConfig} plus the hosted-relay credentials the wallet
10
+ * already holds, and returns a {@link ChainStateProvider}. URL consent is
11
+ * enforced structurally (HTTPS remote, HTTP loopback only) so a hostile node URL
12
+ * cannot be configured silently.
13
+ */
14
+ import type { ChainStateProvider } from './types.js';
15
+ export type ChainProviderMode = 'axia' | 'minima-rpc' | 'composite';
16
+ /** Persisted, user-selectable chain access config. */
17
+ export interface ChainProviderConfig {
18
+ readonly mode: ChainProviderMode;
19
+ /** `http(s)://host:port` for a self-hosted Minima node. */
20
+ readonly minimaRpcUrl?: string;
21
+ readonly minimaRpcUser?: string;
22
+ readonly minimaRpcPass?: string;
23
+ /** Composite only: fall back to the hosted relay on node error. Default true. */
24
+ readonly fallbackToAxia?: boolean;
25
+ }
26
+ export interface HostedRelayConfig {
27
+ readonly baseUrl: string;
28
+ readonly apiKey: string;
29
+ readonly timeoutMs?: number;
30
+ }
31
+ export interface ResolveChainProviderOptions {
32
+ /** Hosted relay credentials (Axia by default). */
33
+ readonly hosted: HostedRelayConfig;
34
+ /** Override hosted provider construction (tests / custom relay). */
35
+ readonly hostedProvider?: ChainStateProvider;
36
+ /** Override node provider construction (tests). */
37
+ readonly createMinimaProvider?: (config: ChainProviderConfig) => ChainStateProvider;
38
+ readonly onFallback?: (method: string, error: unknown) => void;
39
+ /** URL consent check. Defaults to {@link assertConsentedNodeUrl}. */
40
+ readonly validateUrl?: (url: string) => void;
41
+ }
42
+ export interface ParsedMinimaRpcUrl {
43
+ readonly host: string;
44
+ readonly port: number;
45
+ readonly ssl: boolean;
46
+ }
47
+ /** Parse `http(s)://host:port` into the minima-rpc client config shape. */
48
+ export declare function parseMinimaRpcUrl(url: string): ParsedMinimaRpcUrl;
49
+ /**
50
+ * Consent guard (RFC-013 §11): HTTPS is required for remote hosts; plain `http`
51
+ * is permitted only for loopback. Never ships a build-time localhost bypass.
52
+ */
53
+ export declare function assertConsentedNodeUrl(url: string): void;
54
+ /**
55
+ * Resolve a {@link ChainStateProvider} from the persisted config.
56
+ *
57
+ * - `axia` → the hosted relay (default).
58
+ * - `minima-rpc` → the user's own node.
59
+ * - `composite` → node first, hosted fallback (unless `fallbackToAxia === false`).
60
+ */
61
+ export declare function resolveChainProvider(config: ChainProviderConfig, options: ResolveChainProviderOptions): ChainStateProvider;
62
+ /** True when the config routes reads/broadcast away from the hosted relay. */
63
+ export declare function isSelfHosted(config: ChainProviderConfig): boolean;
@@ -0,0 +1,100 @@
1
+ "use strict";
2
+ /**
3
+ * @module @totemsdk/chain-provider/resolve
4
+ *
5
+ * User-selectable chain access (RFC-013 §7). Axia remains the default relay;
6
+ * self-hosted mode resolves reads/broadcast through a user's own Minima node,
7
+ * with an optional composite (node-first, Axia-fallback) mode.
8
+ *
9
+ * The resolver is wallet-agnostic: it takes the persisted
10
+ * {@link ChainProviderConfig} plus the hosted-relay credentials the wallet
11
+ * already holds, and returns a {@link ChainStateProvider}. URL consent is
12
+ * enforced structurally (HTTPS remote, HTTP loopback only) so a hostile node URL
13
+ * cannot be configured silently.
14
+ */
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.parseMinimaRpcUrl = parseMinimaRpcUrl;
17
+ exports.assertConsentedNodeUrl = assertConsentedNodeUrl;
18
+ exports.resolveChainProvider = resolveChainProvider;
19
+ exports.isSelfHosted = isSelfHosted;
20
+ const minima_rpc_1 = require("@totemsdk/minima-rpc");
21
+ const hosted_js_1 = require("./providers/hosted.js");
22
+ const minima_rpc_js_1 = require("./providers/minima-rpc.js");
23
+ const composite_js_1 = require("./providers/composite.js");
24
+ const DEFAULT_RPC_PORT = 9005;
25
+ /** Parse `http(s)://host:port` into the minima-rpc client config shape. */
26
+ function parseMinimaRpcUrl(url) {
27
+ let parsed;
28
+ try {
29
+ parsed = new URL(url);
30
+ }
31
+ catch {
32
+ throw new Error(`Invalid Minima RPC URL: ${url}`);
33
+ }
34
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
35
+ throw new Error('Minima RPC URL must use http: (loopback) or https:');
36
+ }
37
+ const ssl = parsed.protocol === 'https:';
38
+ const port = parsed.port ? Number(parsed.port) : ssl ? 443 : DEFAULT_RPC_PORT;
39
+ if (!Number.isInteger(port) || port <= 0 || port > 65535) {
40
+ throw new Error(`Invalid Minima RPC port in URL: ${url}`);
41
+ }
42
+ return { host: parsed.hostname, port, ssl };
43
+ }
44
+ function isLoopbackHost(hostname) {
45
+ return hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '::1' || hostname === '[::1]';
46
+ }
47
+ /**
48
+ * Consent guard (RFC-013 §11): HTTPS is required for remote hosts; plain `http`
49
+ * is permitted only for loopback. Never ships a build-time localhost bypass.
50
+ */
51
+ function assertConsentedNodeUrl(url) {
52
+ const parsed = new URL(url);
53
+ if (parsed.protocol === 'https:')
54
+ return;
55
+ if (parsed.protocol === 'http:' && isLoopbackHost(parsed.hostname))
56
+ return;
57
+ throw new Error('Self-hosted node URL must use HTTPS. Plain http is allowed only for localhost/127.0.0.1/::1.');
58
+ }
59
+ function createNodeProvider(config) {
60
+ if (!config.minimaRpcUrl) {
61
+ throw new Error('minima-rpc mode requires minimaRpcUrl');
62
+ }
63
+ const { host, port, ssl } = parseMinimaRpcUrl(config.minimaRpcUrl);
64
+ const client = (0, minima_rpc_1.createMinimaRpcClient)({
65
+ host,
66
+ port,
67
+ ssl,
68
+ ...(config.minimaRpcUser ? { username: config.minimaRpcUser } : {}),
69
+ ...(config.minimaRpcPass ? { password: config.minimaRpcPass } : {}),
70
+ });
71
+ return new minima_rpc_js_1.MinimaRpcProvider(client);
72
+ }
73
+ /**
74
+ * Resolve a {@link ChainStateProvider} from the persisted config.
75
+ *
76
+ * - `axia` → the hosted relay (default).
77
+ * - `minima-rpc` → the user's own node.
78
+ * - `composite` → node first, hosted fallback (unless `fallbackToAxia === false`).
79
+ */
80
+ function resolveChainProvider(config, options) {
81
+ const hosted = options.hostedProvider ?? new hosted_js_1.HostedProvider(options.hosted);
82
+ if (config.mode === 'axia') {
83
+ return hosted;
84
+ }
85
+ if (!config.minimaRpcUrl) {
86
+ throw new Error(`chain provider mode "${config.mode}" requires minimaRpcUrl`);
87
+ }
88
+ (options.validateUrl ?? assertConsentedNodeUrl)(config.minimaRpcUrl);
89
+ const node = options.createMinimaProvider
90
+ ? options.createMinimaProvider(config)
91
+ : createNodeProvider(config);
92
+ if (config.mode === 'minima-rpc' || config.fallbackToAxia === false) {
93
+ return node;
94
+ }
95
+ return new composite_js_1.CompositeProvider(node, hosted, options.onFallback);
96
+ }
97
+ /** True when the config routes reads/broadcast away from the hosted relay. */
98
+ function isSelfHosted(config) {
99
+ return config.mode === 'minima-rpc' || config.mode === 'composite';
100
+ }
@@ -0,0 +1,170 @@
1
+ /**
2
+ * @totemsdk/chain-provider — shared types and ChainStateProvider interface
3
+ */
4
+ export interface CoinsQuery {
5
+ address?: string;
6
+ tokenId?: string;
7
+ sendable?: boolean;
8
+ relevant?: boolean;
9
+ coinId?: string;
10
+ megammr?: boolean;
11
+ }
12
+ export interface Coin {
13
+ coinid: string;
14
+ amount: string;
15
+ address: string;
16
+ miniaddress?: string;
17
+ tokenid: string;
18
+ token?: unknown;
19
+ storestate?: boolean;
20
+ state?: unknown[];
21
+ spent?: boolean;
22
+ mmrentry?: string;
23
+ created?: string;
24
+ }
25
+ export interface MMRProof {
26
+ coinid: string;
27
+ data: unknown;
28
+ }
29
+ export interface ChainTip {
30
+ block: number;
31
+ hash: string;
32
+ time?: string;
33
+ }
34
+ export interface TokenInfo {
35
+ tokenid: string;
36
+ name: Record<string, unknown>;
37
+ total?: string;
38
+ confirmed?: string;
39
+ sendable?: string;
40
+ coins?: number;
41
+ script?: string;
42
+ description?: unknown;
43
+ }
44
+ export interface TokenSearchQuery {
45
+ name?: string;
46
+ category?: string[];
47
+ creatorAddress?: string;
48
+ limit?: number;
49
+ offset?: number;
50
+ }
51
+ export interface BroadcastResult {
52
+ txpowid?: string;
53
+ success: boolean;
54
+ message?: string;
55
+ }
56
+ /**
57
+ * Inputs for a live deposit-funding check. "Verified" here means a check against
58
+ * on-chain truth (unspent coin owned by the LP for the claimed token+amount) —
59
+ * never a declared string on a record.
60
+ */
61
+ export interface VerifyDepositParams {
62
+ /** Coin spendable as the funding source. */
63
+ coinId: string;
64
+ /** Address that must own the coin (Mx form; 0x-hex roots are normalized against). */
65
+ ownerAddress: string;
66
+ /** Required token ID; omit to accept base MINIMA. */
67
+ tokenId?: string;
68
+ /** Claimed funding amount (decimal string); coin.amount must be >= this. */
69
+ claimedAmount?: string;
70
+ /** When true, only chain-confirmed coins pass (mmrentry != '0'). */
71
+ requireConfirmed?: boolean;
72
+ }
73
+ /** Granular result of a deposit-funding check. `valid` is the all-gates AND. */
74
+ export interface DepositVerification {
75
+ valid: boolean;
76
+ exists: boolean;
77
+ /** Coin exists and is not spent (on-chain confirm, not declared). */
78
+ unspent: boolean;
79
+ /** Coin is confirmed on-chain (not a mempool entry). */
80
+ confirmed: boolean;
81
+ /** Coin address equals the claimed owner (Mx or 0x-root form). */
82
+ ownedByOwner: boolean;
83
+ /** Coin tokenid matches the requested token (or base token when none given). */
84
+ tokenMatches: boolean;
85
+ /** Coin amount covers the claimed amount. */
86
+ amountSufficient: boolean;
87
+ reason?: string;
88
+ /** The coin as observed on-chain. */
89
+ coin?: Coin;
90
+ error?: unknown;
91
+ }
92
+ /**
93
+ * A chunk-based MMR proof (legacy Minima shape), i.e. the sibling hashes
94
+ * between a leaf and the root. Matches `@totemsdk/core` `MMRProof`.
95
+ */
96
+ export interface MmrChunkProof {
97
+ chunks: Array<{
98
+ isLeft: boolean;
99
+ mmrData: {
100
+ data: Uint8Array;
101
+ value: bigint;
102
+ };
103
+ }>;
104
+ }
105
+ /** Address-derivation policy for LP funding deposits. */
106
+ export interface DepositAddressOptions {
107
+ poolId?: string;
108
+ tokenId?: string;
109
+ }
110
+ /**
111
+ * Optional funding-truth extension port. Providers that can attest deposits
112
+ * implement this; `withDepositVerifier(provider)` provides a default that uses
113
+ * the base provider's `getCoin` for the live path.
114
+ */
115
+ export interface DepositVerifier {
116
+ verifyDeposit(params: VerifyDepositParams): Promise<DepositVerification>;
117
+ /** Deterministic deposit address the LP funds the pool/channel from. */
118
+ depositAddressFor(lp: string, opts?: DepositAddressOptions): string;
119
+ /** Chain MMR root for offline proof verification; null when unavailable. */
120
+ getMmrRoot(): Promise<string | null>;
121
+ /** Offline (root-anchored) proof check; falls back to the live path when absent. */
122
+ verifyMmrDeposit?(params: {
123
+ leafPubkey: Uint8Array;
124
+ proof: MmrChunkProof;
125
+ expectedRoot: Uint8Array;
126
+ }): Promise<boolean>;
127
+ }
128
+ export interface AddressInfo {
129
+ address: string;
130
+ publickey: string;
131
+ script: string;
132
+ }
133
+ export interface ExportedCoin {
134
+ coinid: string;
135
+ data: string;
136
+ }
137
+ export interface ChainStateProvider {
138
+ getCoins(query: CoinsQuery): Promise<Coin[]>;
139
+ /**
140
+ * Ownership material for an address (public key + address script). Required to
141
+ * build a funding witness for a coin the caller owns.
142
+ */
143
+ getAddressInfo?(address: string): Promise<AddressInfo | null>;
144
+ /**
145
+ * Serialized coin proof (Minima `coinexport`) for a specific coin id. Required
146
+ * to assemble the funding input proof. Never expose this over a remote control
147
+ * plane; it is caller-side material.
148
+ */
149
+ exportCoin?(coinId: string): Promise<ExportedCoin | null>;
150
+ getCoin(coinId: string): Promise<Coin | null>;
151
+ getProof(coinId: string): Promise<MMRProof>;
152
+ getTip(): Promise<ChainTip>;
153
+ getToken(tokenId: string): Promise<TokenInfo>;
154
+ searchTokens(query: TokenSearchQuery): Promise<TokenInfo[]>;
155
+ getTokensByCreator(address: string): Promise<TokenInfo[]>;
156
+ broadcastTxPoW(txpowHex: string): Promise<BroadcastResult>;
157
+ /**
158
+ * Live minimum TxPoW work (32-byte hex target) from the node's Magic numbers.
159
+ * Optional: providers that cannot read it let callers fall back to the
160
+ * protocol default. Used to mine transactions to the current network target.
161
+ */
162
+ getMinTxPowWork?(): Promise<string | null>;
163
+ /**
164
+ * Submit a raw transaction + witness through the node's explicit-mine path:
165
+ * `txnmine` (node builds the TxPoW header with the real block number /
166
+ * difficulty / magic and mines) followed by `sendtransaction`. When absent,
167
+ * callers fall back to SDK-side mining + `broadcastTxPoW`.
168
+ */
169
+ submitTransaction?(txBytes: Uint8Array, witnessBytes: Uint8Array, id?: string): Promise<BroadcastResult>;
170
+ }
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ /**
3
+ * @totemsdk/chain-provider — shared types and ChainStateProvider interface
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,53 @@
1
+ /**
2
+ * chain-provider/verify-deposit.ts — Funding-truth verification.
3
+ *
4
+ * "Verified every time means on-chain check," so this module is the single
5
+ * place a deposit's funding is checked: an unspent coin, owned by the LP,
6
+ * for the claimed token and amount. The offline variant anchors a legacy
7
+ * chunk MMR proof against a known root so a peer with a lookup root can
8
+ * re-validate a deposit without reaching the node.
9
+ */
10
+ import type { ChainStateProvider, Coin, DepositAddressOptions, DepositVerification, DepositVerifier, MmrChunkProof, VerifyDepositParams } from './types.js';
11
+ export declare const DEPOSIT_ADDRESS_DOMAIN = "totemsdk/chain-provider/deposit/v1";
12
+ /**
13
+ * The shared all-gates deposit evaluation. Used by the generic `verifyDeposit`
14
+ * and by `MinimaRpcProvider` (which reads the coin proof via `coinexport`).
15
+ */
16
+ export declare function evaluateDeposit(coin: Coin, spent: boolean, params: VerifyDepositParams): DepositVerification;
17
+ export declare function notFoundResult(reason: string): DepositVerification;
18
+ /**
19
+ * Live deposit check against a chain provider. All gates must hold:
20
+ * 1. the coin exists;
21
+ * 2. it is unspent (confirmed on-chain, never a declared flag);
22
+ * 3. it is owned by `ownerAddress` (Mx or 0x-root form);
23
+ * 4. its tokenid matches (base MINIMA = '0x00' when none is requested);
24
+ * 5. its amount covers `claimedAmount`;
25
+ * 6. when `requireConfirmed` is set, the coin is chain-confirmed.
26
+ */
27
+ export declare function verifyDeposit(provider: Pick<ChainStateProvider, 'getCoin'>, params: VerifyDepositParams): Promise<DepositVerification>;
28
+ /**
29
+ * Offline verification of a legacy chunk MMR proof against an expected root.
30
+ * Pure function — a peer holding (leafPubkey, proof, root) can re-validate a
31
+ * deposit commitment without node access. The proof is encoded to the wasm
32
+ * contract (hex `data`, decimal-string `value` per chunk).
33
+ */
34
+ export declare function verifyDepositMmrProof(leafPubkey: Uint8Array, proof: MmrChunkProof, expectedRoot: Uint8Array): boolean;
35
+ /**
36
+ * Deterministic, domain-separated funding address for an LP deposit. In
37
+ * production this is the channel/pool script address the LP pays into and the
38
+ * funding check is run against; keeping it a pure derivation keeps issue #25
39
+ * constructable and checkable without a live script compiler.
40
+ */
41
+ export declare function depositAddressFor(lp: string, opts?: DepositAddressOptions): string;
42
+ /**
43
+ * Default `DepositVerifier` over any `ChainStateProvider`. The live path uses
44
+ * `getCoin`; the MMR-root path returns `null` unless the base provider knows a
45
+ * root (concrete providers override `getMmrRoot`).
46
+ */
47
+ export declare function withDepositVerifier(provider: ChainStateProvider): ChainStateProvider & DepositVerifier;
48
+ /**
49
+ * Compare two decimal amounts exactly at a common scale derived from the
50
+ * inputs. Neither side is fixed-truncated, so a claim can never be rounded
51
+ * down into passing (AUD-038).
52
+ */
53
+ export declare function compareAmounts(a: string, b: string): number;
@@ -0,0 +1,212 @@
1
+ "use strict";
2
+ /**
3
+ * chain-provider/verify-deposit.ts — Funding-truth verification.
4
+ *
5
+ * "Verified every time means on-chain check," so this module is the single
6
+ * place a deposit's funding is checked: an unspent coin, owned by the LP,
7
+ * for the claimed token and amount. The offline variant anchors a legacy
8
+ * chunk MMR proof against a known root so a peer with a lookup root can
9
+ * re-validate a deposit without reaching the node.
10
+ */
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.DEPOSIT_ADDRESS_DOMAIN = void 0;
13
+ exports.evaluateDeposit = evaluateDeposit;
14
+ exports.notFoundResult = notFoundResult;
15
+ exports.verifyDeposit = verifyDeposit;
16
+ exports.verifyDepositMmrProof = verifyDepositMmrProof;
17
+ exports.depositAddressFor = depositAddressFor;
18
+ exports.withDepositVerifier = withDepositVerifier;
19
+ exports.compareAmounts = compareAmounts;
20
+ const core_1 = require("@totemsdk/core");
21
+ exports.DEPOSIT_ADDRESS_DOMAIN = 'totemsdk/chain-provider/deposit/v1';
22
+ /** Reduce an address to its root bytes: Mx addresses decode, 0x-hex roots pass through. */
23
+ function rootBytesOf(value) {
24
+ const v = value.trim();
25
+ if (/^[0-9a-fA-F]{64}$/.test(v.replace(/^0x/, ''))) {
26
+ return (0, core_1.hexToBytes)(v);
27
+ }
28
+ try {
29
+ return (0, core_1.decodeMx)(v);
30
+ }
31
+ catch {
32
+ return null;
33
+ }
34
+ }
35
+ function bytesEqual(a, b) {
36
+ return a.length === b.length && a.every((x, i) => x === b[i]);
37
+ }
38
+ /**
39
+ * Normalize ownership comparison (#2): totem-node reports `address`/`miniaddress`
40
+ * as 0x-hex script roots while LPs hold Mx addresses. Either form compares equal.
41
+ */
42
+ function addressesEqual(a, b) {
43
+ if (a === b)
44
+ return true;
45
+ const ra = rootBytesOf(a);
46
+ const rb = rootBytesOf(b);
47
+ return !!ra && !!rb && bytesEqual(ra, rb);
48
+ }
49
+ /**
50
+ * Is the coin chain-confirmed? (#7) An unspent coin in the node's mempool has
51
+ * mmrentry '0' and can still be double-spent. treat anything without a positive
52
+ * mmrentry as unconfirmed.
53
+ */
54
+ function isConfirmed(coin) {
55
+ const entry = coin.mmrentry;
56
+ if (entry === undefined || entry === null)
57
+ return false;
58
+ const num = parseInt(String(entry), 10);
59
+ return Number.isFinite(num) && num > 0;
60
+ }
61
+ /**
62
+ * The shared all-gates deposit evaluation. Used by the generic `verifyDeposit`
63
+ * and by `MinimaRpcProvider` (which reads the coin proof via `coinexport`).
64
+ */
65
+ function evaluateDeposit(coin, spent, params) {
66
+ const unspent = spent !== true && coin.spent !== true;
67
+ const ownedByOwner = addressesEqual(coin.address, params.ownerAddress) || addressesEqual(coin.miniaddress ?? coin.address, params.ownerAddress);
68
+ const tokenMatches = params.tokenId ? coin.tokenid === params.tokenId : coin.tokenid === '0x00' || coin.tokenid === '0x01';
69
+ const amountSufficient = params.claimedAmount === undefined || compareAmounts(coin.amount, params.claimedAmount) >= 0;
70
+ const confirmed = isConfirmed(coin);
71
+ const gates = [unspent, ownedByOwner, tokenMatches, amountSufficient];
72
+ if (params.requireConfirmed)
73
+ gates.push(confirmed);
74
+ return {
75
+ valid: gates.every(Boolean),
76
+ exists: true,
77
+ unspent,
78
+ confirmed,
79
+ ownedByOwner,
80
+ tokenMatches,
81
+ amountSufficient,
82
+ reason: gates.every(Boolean) ? undefined : 'deposit funding check failed',
83
+ coin,
84
+ };
85
+ }
86
+ function notFoundResult(reason) {
87
+ return {
88
+ valid: false,
89
+ exists: false,
90
+ unspent: false,
91
+ confirmed: false,
92
+ ownedByOwner: false,
93
+ tokenMatches: false,
94
+ amountSufficient: false,
95
+ reason,
96
+ };
97
+ }
98
+ /**
99
+ * Live deposit check against a chain provider. All gates must hold:
100
+ * 1. the coin exists;
101
+ * 2. it is unspent (confirmed on-chain, never a declared flag);
102
+ * 3. it is owned by `ownerAddress` (Mx or 0x-root form);
103
+ * 4. its tokenid matches (base MINIMA = '0x00' when none is requested);
104
+ * 5. its amount covers `claimedAmount`;
105
+ * 6. when `requireConfirmed` is set, the coin is chain-confirmed.
106
+ */
107
+ async function verifyDeposit(provider, params) {
108
+ let coin;
109
+ try {
110
+ coin = await provider.getCoin(params.coinId);
111
+ }
112
+ catch (error) {
113
+ return {
114
+ valid: false,
115
+ exists: false,
116
+ unspent: false,
117
+ confirmed: false,
118
+ ownedByOwner: false,
119
+ tokenMatches: false,
120
+ amountSufficient: false,
121
+ reason: 'unable to reach chain provider',
122
+ error,
123
+ };
124
+ }
125
+ if (!coin) {
126
+ return notFoundResult(`coin ${params.coinId} not found on chain`);
127
+ }
128
+ return evaluateDeposit(coin, coin.spent === true, params);
129
+ }
130
+ /**
131
+ * Offline verification of a legacy chunk MMR proof against an expected root.
132
+ * Pure function — a peer holding (leafPubkey, proof, root) can re-validate a
133
+ * deposit commitment without node access. The proof is encoded to the wasm
134
+ * contract (hex `data`, decimal-string `value` per chunk).
135
+ */
136
+ function verifyDepositMmrProof(leafPubkey, proof, expectedRoot) {
137
+ const proofJson = JSON.stringify({
138
+ chunks: proof.chunks.map((c) => ({
139
+ isLeft: c.isLeft,
140
+ mmrData: {
141
+ data: (0, core_1.bytesToHex)(c.mmrData.data),
142
+ value: c.mmrData.value.toString(),
143
+ },
144
+ })),
145
+ });
146
+ return (0, core_1.verifyMMRProof)(leafPubkey, proofJson, expectedRoot);
147
+ }
148
+ /**
149
+ * Deterministic, domain-separated funding address for an LP deposit. In
150
+ * production this is the channel/pool script address the LP pays into and the
151
+ * funding check is run against; keeping it a pure derivation keeps issue #25
152
+ * constructable and checkable without a live script compiler.
153
+ */
154
+ function depositAddressFor(lp, opts) {
155
+ const scope = [
156
+ exports.DEPOSIT_ADDRESS_DOMAIN,
157
+ lp,
158
+ opts?.poolId ?? '',
159
+ opts?.tokenId ?? '0x00',
160
+ ].join('|');
161
+ return `Mx${(0, core_1.toHex)((0, core_1.sha3_256)(new TextEncoder().encode(scope))).slice(0, 80)}`;
162
+ }
163
+ /**
164
+ * Default `DepositVerifier` over any `ChainStateProvider`. The live path uses
165
+ * `getCoin`; the MMR-root path returns `null` unless the base provider knows a
166
+ * root (concrete providers override `getMmrRoot`).
167
+ */
168
+ function withDepositVerifier(provider) {
169
+ const verifier = {
170
+ verifyDeposit: (params) => verifyDeposit(provider, params),
171
+ depositAddressFor,
172
+ getMmrRoot: async () => null,
173
+ verifyMmrDeposit: (params) => Promise.resolve(verifyDepositMmrProof(params.leafPubkey, params.proof, params.expectedRoot)),
174
+ };
175
+ // Prototype-chain the wrapper onto the provider so class methods stay
176
+ // reachable and `this` still resolves against the original instance (AUD-039).
177
+ return Object.assign(Object.create(provider), verifier);
178
+ }
179
+ /**
180
+ * Parse a decimal amount — possibly a MiniNumber "decimal.uuid" string — into
181
+ * its whole part and full fractional digit string. The numeric prefix is used
182
+ * and fractional precision is preserved, never truncated (AUD-038).
183
+ */
184
+ function splitAmount(decimalOrMinima) {
185
+ const match = /^([0-9]+(?:\.[0-9]+)?)/.exec(decimalOrMinima.trim());
186
+ const num = match ? match[1] : decimalOrMinima.trim();
187
+ if (!num || !/^[0-9]+(\.[0-9]+)?$/.test(num))
188
+ return { whole: 0n, frac: '' };
189
+ const [whole, frac] = num.split('.');
190
+ return { whole: BigInt(whole), frac: frac ?? '' };
191
+ }
192
+ /**
193
+ * Compare two decimal amounts exactly at a common scale derived from the
194
+ * inputs. Neither side is fixed-truncated, so a claim can never be rounded
195
+ * down into passing (AUD-038).
196
+ */
197
+ function compareAmounts(a, b) {
198
+ const left = splitAmount(a);
199
+ const right = splitAmount(b);
200
+ if (left.whole < right.whole)
201
+ return -1;
202
+ if (left.whole > right.whole)
203
+ return 1;
204
+ const scale = Math.max(left.frac.length, right.frac.length);
205
+ const leftFrac = BigInt(left.frac.padEnd(scale, '0') || '0');
206
+ const rightFrac = BigInt(right.frac.padEnd(scale, '0') || '0');
207
+ if (leftFrac < rightFrac)
208
+ return -1;
209
+ if (leftFrac > rightFrac)
210
+ return 1;
211
+ return 0;
212
+ }
package/dist/index.js CHANGED
@@ -1,22 +1,6 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isSelfHosted = exports.assertConsentedNodeUrl = exports.parseMinimaRpcUrl = exports.resolveChainProvider = exports.CompositeProvider = exports.LookupClientProvider = exports.MinimaRpcProvider = exports.HostedProvider = exports.withDepositVerifier = exports.verifyDepositMmrProof = exports.verifyDeposit = exports.depositAddressFor = exports.DEPOSIT_ADDRESS_DOMAIN = void 0;
4
- var verify_deposit_js_1 = require("./verify-deposit.js");
5
- Object.defineProperty(exports, "DEPOSIT_ADDRESS_DOMAIN", { enumerable: true, get: function () { return verify_deposit_js_1.DEPOSIT_ADDRESS_DOMAIN; } });
6
- Object.defineProperty(exports, "depositAddressFor", { enumerable: true, get: function () { return verify_deposit_js_1.depositAddressFor; } });
7
- Object.defineProperty(exports, "verifyDeposit", { enumerable: true, get: function () { return verify_deposit_js_1.verifyDeposit; } });
8
- Object.defineProperty(exports, "verifyDepositMmrProof", { enumerable: true, get: function () { return verify_deposit_js_1.verifyDepositMmrProof; } });
9
- Object.defineProperty(exports, "withDepositVerifier", { enumerable: true, get: function () { return verify_deposit_js_1.withDepositVerifier; } });
10
- var hosted_js_1 = require("./providers/hosted.js");
11
- Object.defineProperty(exports, "HostedProvider", { enumerable: true, get: function () { return hosted_js_1.HostedProvider; } });
12
- var minima_rpc_js_1 = require("./providers/minima-rpc.js");
13
- Object.defineProperty(exports, "MinimaRpcProvider", { enumerable: true, get: function () { return minima_rpc_js_1.MinimaRpcProvider; } });
14
- var lookup_client_js_1 = require("./providers/lookup-client.js");
15
- Object.defineProperty(exports, "LookupClientProvider", { enumerable: true, get: function () { return lookup_client_js_1.LookupClientProvider; } });
16
- var composite_js_1 = require("./providers/composite.js");
17
- Object.defineProperty(exports, "CompositeProvider", { enumerable: true, get: function () { return composite_js_1.CompositeProvider; } });
18
- var resolve_js_1 = require("./resolve.js");
19
- Object.defineProperty(exports, "resolveChainProvider", { enumerable: true, get: function () { return resolve_js_1.resolveChainProvider; } });
20
- Object.defineProperty(exports, "parseMinimaRpcUrl", { enumerable: true, get: function () { return resolve_js_1.parseMinimaRpcUrl; } });
21
- Object.defineProperty(exports, "assertConsentedNodeUrl", { enumerable: true, get: function () { return resolve_js_1.assertConsentedNodeUrl; } });
22
- Object.defineProperty(exports, "isSelfHosted", { enumerable: true, get: function () { return resolve_js_1.isSelfHosted; } });
1
+ export { DEPOSIT_ADDRESS_DOMAIN, depositAddressFor, verifyDeposit, verifyDepositMmrProof, withDepositVerifier, } from './verify-deposit.js';
2
+ export { HostedProvider } from './providers/hosted.js';
3
+ export { MinimaRpcProvider } from './providers/minima-rpc.js';
4
+ export { LookupClientProvider } from './providers/lookup-client.js';
5
+ export { CompositeProvider } from './providers/composite.js';
6
+ export { resolveChainProvider, parseMinimaRpcUrl, assertConsentedNodeUrl, isSelfHosted, } from './resolve.js';
@@ -1,10 +1,7 @@
1
- "use strict";
2
1
  /**
3
2
  * CompositeProvider — tries primary provider, falls back to secondary on any error.
4
3
  */
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.CompositeProvider = void 0;
7
- class CompositeProvider {
4
+ export class CompositeProvider {
8
5
  constructor(primary, fallback, onFallback) {
9
6
  this.primary = primary;
10
7
  this.fallback = fallback;
@@ -51,4 +48,3 @@ class CompositeProvider {
51
48
  return this.withArg('broadcastTxPoW', txpowHex);
52
49
  }
53
50
  }
54
- exports.CompositeProvider = CompositeProvider;
@@ -1,4 +1,3 @@
1
- "use strict";
2
1
  /**
3
2
  * HostedProvider — wraps Axia REST + RPC API endpoints.
4
3
  *
@@ -10,8 +9,6 @@
10
9
  * For dApp developers using custom project API keys the `/v1/wallet/*` routes
11
10
  * require x-api-key: 'totem-shared'. Use the apiKey config option accordingly.
12
11
  */
13
- Object.defineProperty(exports, "__esModule", { value: true });
14
- exports.HostedProvider = void 0;
15
12
  function sanitizeRpcParam(value, name) {
16
13
  if (value.length > 1024) {
17
14
  throw new Error(`RPC parameter ${name} exceeds maximum length (1024)`);
@@ -25,7 +22,7 @@ function sanitizeRpcParam(value, name) {
25
22
  }
26
23
  return trimmed;
27
24
  }
28
- class HostedProvider {
25
+ export class HostedProvider {
29
26
  constructor(config) {
30
27
  this.baseUrl = config.baseUrl.replace(/\/$/, '');
31
28
  if (!this.baseUrl.startsWith('https://')) {
@@ -240,4 +237,3 @@ class HostedProvider {
240
237
  };
241
238
  }
242
239
  }
243
- exports.HostedProvider = HostedProvider;