@totemsdk/chain-provider 0.2.0 → 0.2.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.
package/dist/index.d.ts CHANGED
@@ -1,7 +1,10 @@
1
- export type { ChainStateProvider, CoinsQuery, Coin, MMRProof, ChainTip, TokenInfo, TokenSearchQuery, BroadcastResult, } from './types.js';
1
+ export type { ChainStateProvider, CoinsQuery, Coin, MMRProof, ChainTip, TokenInfo, TokenSearchQuery, BroadcastResult, VerifyDepositParams, DepositVerification, MmrChunkProof, DepositAddressOptions, DepositVerifier, } from './types.js';
2
+ export { DEPOSIT_ADDRESS_DOMAIN, depositAddressFor, verifyDeposit, verifyDepositMmrProof, withDepositVerifier, } from './verify-deposit.js';
2
3
  export { HostedProvider } from './providers/hosted.js';
3
4
  export type { HostedProviderConfig } from './providers/hosted.js';
4
5
  export { MinimaRpcProvider } from './providers/minima-rpc.js';
5
6
  export { LookupClientProvider } from './providers/lookup-client.js';
6
7
  export type { LookupClientLike } from './providers/lookup-client.js';
7
8
  export { CompositeProvider } from './providers/composite.js';
9
+ export { resolveChainProvider, parseMinimaRpcUrl, assertConsentedNodeUrl, isSelfHosted, } from './resolve.js';
10
+ export type { ChainProviderMode, ChainProviderConfig, HostedRelayConfig, ResolveChainProviderOptions, ParsedMinimaRpcUrl, } from './resolve.js';
package/dist/index.js CHANGED
@@ -1,6 +1,12 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.CompositeProvider = exports.LookupClientProvider = exports.MinimaRpcProvider = exports.HostedProvider = void 0;
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; } });
4
10
  var hosted_js_1 = require("./providers/hosted.js");
5
11
  Object.defineProperty(exports, "HostedProvider", { enumerable: true, get: function () { return hosted_js_1.HostedProvider; } });
6
12
  var minima_rpc_js_1 = require("./providers/minima-rpc.js");
@@ -9,3 +15,8 @@ var lookup_client_js_1 = require("./providers/lookup-client.js");
9
15
  Object.defineProperty(exports, "LookupClientProvider", { enumerable: true, get: function () { return lookup_client_js_1.LookupClientProvider; } });
10
16
  var composite_js_1 = require("./providers/composite.js");
11
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; } });
@@ -2,12 +2,25 @@
2
2
  * MinimaRpcProvider — thin wrapper over @totemsdk/minima-rpc.
3
3
  */
4
4
  import type { MinimaRpcClient } from '@totemsdk/minima-rpc';
5
- import type { ChainStateProvider, CoinsQuery, Coin, MMRProof, ChainTip, TokenInfo, TokenSearchQuery, BroadcastResult } from '../types.js';
6
- export declare class MinimaRpcProvider implements ChainStateProvider {
5
+ import type { ChainStateProvider, CoinsQuery, Coin, MMRProof, ChainTip, TokenInfo, TokenSearchQuery, BroadcastResult, DepositVerifier, VerifyDepositParams, DepositVerification } from '../types.js';
6
+ export declare class MinimaRpcProvider implements ChainStateProvider, DepositVerifier {
7
7
  private readonly client;
8
8
  constructor(client: MinimaRpcClient);
9
9
  getCoins(query: CoinsQuery): Promise<Coin[]>;
10
10
  getCoin(coinId: string): Promise<Coin | null>;
11
+ /**
12
+ * Authoritative live check via `coinexport` (the coinproof endpoint): returns
13
+ * found/unspent/owned/token/amount + the full coin proof. `coincheck` on
14
+ * totem-node wants a full proof payload rather than a coinid, so coinexport
15
+ * is the canonical primitive (#3).
16
+ */
17
+ verifyDeposit(params: VerifyDepositParams): Promise<DepositVerification>;
18
+ depositAddressFor(lp: string, opts?: {
19
+ poolId?: string;
20
+ tokenId?: string;
21
+ }): string;
22
+ /** MMR root at tip — the anchor peers verify offline proofs against. */
23
+ getMmrRoot(): Promise<string | null>;
11
24
  getProof(coinId: string): Promise<MMRProof>;
12
25
  getTip(): Promise<ChainTip>;
13
26
  getToken(tokenId: string): Promise<TokenInfo>;
@@ -4,6 +4,7 @@
4
4
  */
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.MinimaRpcProvider = void 0;
7
+ const verify_deposit_js_1 = require("../verify-deposit.js");
7
8
  class MinimaRpcProvider {
8
9
  constructor(client) {
9
10
  this.client = client;
@@ -28,6 +29,44 @@ class MinimaRpcProvider {
28
29
  return null;
29
30
  }
30
31
  }
32
+ /**
33
+ * Authoritative live check via `coinexport` (the coinproof endpoint): returns
34
+ * found/unspent/owned/token/amount + the full coin proof. `coincheck` on
35
+ * totem-node wants a full proof payload rather than a coinid, so coinexport
36
+ * is the canonical primitive (#3).
37
+ */
38
+ async verifyDeposit(params) {
39
+ try {
40
+ const exported = await this.client.coinExport(params.coinId);
41
+ const coin = exported?.coinproof?.coin;
42
+ const spent = coin?.spent === true;
43
+ if (!coin) {
44
+ return (0, verify_deposit_js_1.notFoundResult)(`coin ${params.coinId} not found on chain`);
45
+ }
46
+ return (0, verify_deposit_js_1.evaluateDeposit)(coin, spent, params);
47
+ }
48
+ catch (error) {
49
+ return {
50
+ valid: false,
51
+ exists: false,
52
+ unspent: false,
53
+ confirmed: false,
54
+ ownedByOwner: false,
55
+ tokenMatches: false,
56
+ amountSufficient: false,
57
+ reason: 'unable to reach chain provider',
58
+ error,
59
+ };
60
+ }
61
+ }
62
+ depositAddressFor(lp, opts) {
63
+ return (0, verify_deposit_js_1.depositAddressFor)(lp, opts);
64
+ }
65
+ /** MMR root at tip — the anchor peers verify offline proofs against. */
66
+ async getMmrRoot() {
67
+ const info = await this.client.megammr();
68
+ return info?.hash ?? null;
69
+ }
31
70
  async getProof(coinId) {
32
71
  return this.client.mmrProof(coinId);
33
72
  }
@@ -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
+ }
package/dist/types.d.ts CHANGED
@@ -53,6 +53,78 @@ export interface BroadcastResult {
53
53
  success: boolean;
54
54
  message?: string;
55
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
+ }
56
128
  export interface ChainStateProvider {
57
129
  getCoins(query: CoinsQuery): Promise<Coin[]>;
58
130
  getCoin(coinId: string): Promise<Coin | null>;
@@ -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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@totemsdk/chain-provider",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "Unified ChainStateProvider interface for Totem SDK — Hosted, Minima RPC, Composite",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -17,8 +17,8 @@
17
17
  "LICENSE"
18
18
  ],
19
19
  "dependencies": {
20
- "@totemsdk/core": "^1.2.9",
21
- "@totemsdk/minima-rpc": "^0.2.0"
20
+ "@totemsdk/minima-rpc": "^0.2.2",
21
+ "@totemsdk/core": "^1.2.11"
22
22
  },
23
23
  "devDependencies": {
24
24
  "@types/jest": "^30.0.0",
@@ -35,7 +35,7 @@
35
35
  },
36
36
  "license": "MIT",
37
37
  "author": "Totem SDK",
38
- "homepage": "https://totem.ing",
38
+ "homepage": "https://docs.totem.ing",
39
39
  "bugs": {
40
40
  "url": "https://github.com/Totem-Edge/totem-sdk/issues"
41
41
  },