@totemsdk/chain-provider 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/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>;
@@ -62,4 +134,17 @@ export interface ChainStateProvider {
62
134
  searchTokens(query: TokenSearchQuery): Promise<TokenInfo[]>;
63
135
  getTokensByCreator(address: string): Promise<TokenInfo[]>;
64
136
  broadcastTxPoW(txpowHex: string): Promise<BroadcastResult>;
137
+ /**
138
+ * Live minimum TxPoW work (32-byte hex target) from the node's Magic numbers.
139
+ * Optional: providers that cannot read it let callers fall back to the
140
+ * protocol default. Used to mine transactions to the current network target.
141
+ */
142
+ getMinTxPowWork?(): Promise<string | null>;
143
+ /**
144
+ * Submit a raw transaction + witness through the node's explicit-mine path:
145
+ * `txnmine` (node builds the TxPoW header with the real block number /
146
+ * difficulty / magic and mines) followed by `sendtransaction`. When absent,
147
+ * callers fall back to SDK-side mining + `broadcastTxPoW`.
148
+ */
149
+ submitTransaction?(txBytes: Uint8Array, witnessBytes: Uint8Array, id?: string): Promise<BroadcastResult>;
65
150
  }
package/dist/types.js CHANGED
@@ -1,5 +1,4 @@
1
- "use strict";
2
1
  /**
3
2
  * @totemsdk/chain-provider — shared types and ChainStateProvider interface
4
3
  */
5
- Object.defineProperty(exports, "__esModule", { value: true });
4
+ export {};
@@ -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,202 @@
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 { bytesToHex, decodeMx, hexToBytes, sha3_256, toHex, verifyMMRProof } from '@totemsdk/core';
11
+ export const DEPOSIT_ADDRESS_DOMAIN = 'totemsdk/chain-provider/deposit/v1';
12
+ /** Reduce an address to its root bytes: Mx addresses decode, 0x-hex roots pass through. */
13
+ function rootBytesOf(value) {
14
+ const v = value.trim();
15
+ if (/^[0-9a-fA-F]{64}$/.test(v.replace(/^0x/, ''))) {
16
+ return hexToBytes(v);
17
+ }
18
+ try {
19
+ return decodeMx(v);
20
+ }
21
+ catch {
22
+ return null;
23
+ }
24
+ }
25
+ function bytesEqual(a, b) {
26
+ return a.length === b.length && a.every((x, i) => x === b[i]);
27
+ }
28
+ /**
29
+ * Normalize ownership comparison (#2): totem-node reports `address`/`miniaddress`
30
+ * as 0x-hex script roots while LPs hold Mx addresses. Either form compares equal.
31
+ */
32
+ function addressesEqual(a, b) {
33
+ if (a === b)
34
+ return true;
35
+ const ra = rootBytesOf(a);
36
+ const rb = rootBytesOf(b);
37
+ return !!ra && !!rb && bytesEqual(ra, rb);
38
+ }
39
+ /**
40
+ * Is the coin chain-confirmed? (#7) An unspent coin in the node's mempool has
41
+ * mmrentry '0' and can still be double-spent. treat anything without a positive
42
+ * mmrentry as unconfirmed.
43
+ */
44
+ function isConfirmed(coin) {
45
+ const entry = coin.mmrentry;
46
+ if (entry === undefined || entry === null)
47
+ return false;
48
+ const num = parseInt(String(entry), 10);
49
+ return Number.isFinite(num) && num > 0;
50
+ }
51
+ /**
52
+ * The shared all-gates deposit evaluation. Used by the generic `verifyDeposit`
53
+ * and by `MinimaRpcProvider` (which reads the coin proof via `coinexport`).
54
+ */
55
+ export function evaluateDeposit(coin, spent, params) {
56
+ const unspent = spent !== true && coin.spent !== true;
57
+ const ownedByOwner = addressesEqual(coin.address, params.ownerAddress) || addressesEqual(coin.miniaddress ?? coin.address, params.ownerAddress);
58
+ const tokenMatches = params.tokenId ? coin.tokenid === params.tokenId : coin.tokenid === '0x00' || coin.tokenid === '0x01';
59
+ const amountSufficient = params.claimedAmount === undefined || compareAmounts(coin.amount, params.claimedAmount) >= 0;
60
+ const confirmed = isConfirmed(coin);
61
+ const gates = [unspent, ownedByOwner, tokenMatches, amountSufficient];
62
+ if (params.requireConfirmed)
63
+ gates.push(confirmed);
64
+ return {
65
+ valid: gates.every(Boolean),
66
+ exists: true,
67
+ unspent,
68
+ confirmed,
69
+ ownedByOwner,
70
+ tokenMatches,
71
+ amountSufficient,
72
+ reason: gates.every(Boolean) ? undefined : 'deposit funding check failed',
73
+ coin,
74
+ };
75
+ }
76
+ export function notFoundResult(reason) {
77
+ return {
78
+ valid: false,
79
+ exists: false,
80
+ unspent: false,
81
+ confirmed: false,
82
+ ownedByOwner: false,
83
+ tokenMatches: false,
84
+ amountSufficient: false,
85
+ reason,
86
+ };
87
+ }
88
+ /**
89
+ * Live deposit check against a chain provider. All gates must hold:
90
+ * 1. the coin exists;
91
+ * 2. it is unspent (confirmed on-chain, never a declared flag);
92
+ * 3. it is owned by `ownerAddress` (Mx or 0x-root form);
93
+ * 4. its tokenid matches (base MINIMA = '0x00' when none is requested);
94
+ * 5. its amount covers `claimedAmount`;
95
+ * 6. when `requireConfirmed` is set, the coin is chain-confirmed.
96
+ */
97
+ export async function verifyDeposit(provider, params) {
98
+ let coin;
99
+ try {
100
+ coin = await provider.getCoin(params.coinId);
101
+ }
102
+ catch (error) {
103
+ return {
104
+ valid: false,
105
+ exists: false,
106
+ unspent: false,
107
+ confirmed: false,
108
+ ownedByOwner: false,
109
+ tokenMatches: false,
110
+ amountSufficient: false,
111
+ reason: 'unable to reach chain provider',
112
+ error,
113
+ };
114
+ }
115
+ if (!coin) {
116
+ return notFoundResult(`coin ${params.coinId} not found on chain`);
117
+ }
118
+ return evaluateDeposit(coin, coin.spent === true, params);
119
+ }
120
+ /**
121
+ * Offline verification of a legacy chunk MMR proof against an expected root.
122
+ * Pure function — a peer holding (leafPubkey, proof, root) can re-validate a
123
+ * deposit commitment without node access. The proof is encoded to the wasm
124
+ * contract (hex `data`, decimal-string `value` per chunk).
125
+ */
126
+ export function verifyDepositMmrProof(leafPubkey, proof, expectedRoot) {
127
+ const proofJson = JSON.stringify({
128
+ chunks: proof.chunks.map((c) => ({
129
+ isLeft: c.isLeft,
130
+ mmrData: {
131
+ data: bytesToHex(c.mmrData.data),
132
+ value: c.mmrData.value.toString(),
133
+ },
134
+ })),
135
+ });
136
+ return verifyMMRProof(leafPubkey, proofJson, expectedRoot);
137
+ }
138
+ /**
139
+ * Deterministic, domain-separated funding address for an LP deposit. In
140
+ * production this is the channel/pool script address the LP pays into and the
141
+ * funding check is run against; keeping it a pure derivation keeps issue #25
142
+ * constructable and checkable without a live script compiler.
143
+ */
144
+ export function depositAddressFor(lp, opts) {
145
+ const scope = [
146
+ DEPOSIT_ADDRESS_DOMAIN,
147
+ lp,
148
+ opts?.poolId ?? '',
149
+ opts?.tokenId ?? '0x00',
150
+ ].join('|');
151
+ return `Mx${toHex(sha3_256(new TextEncoder().encode(scope))).slice(0, 80)}`;
152
+ }
153
+ /**
154
+ * Default `DepositVerifier` over any `ChainStateProvider`. The live path uses
155
+ * `getCoin`; the MMR-root path returns `null` unless the base provider knows a
156
+ * root (concrete providers override `getMmrRoot`).
157
+ */
158
+ export function withDepositVerifier(provider) {
159
+ const verifier = {
160
+ verifyDeposit: (params) => verifyDeposit(provider, params),
161
+ depositAddressFor,
162
+ getMmrRoot: async () => null,
163
+ verifyMmrDeposit: (params) => Promise.resolve(verifyDepositMmrProof(params.leafPubkey, params.proof, params.expectedRoot)),
164
+ };
165
+ // Prototype-chain the wrapper onto the provider so class methods stay
166
+ // reachable and `this` still resolves against the original instance (AUD-039).
167
+ return Object.assign(Object.create(provider), verifier);
168
+ }
169
+ /**
170
+ * Parse a decimal amount — possibly a MiniNumber "decimal.uuid" string — into
171
+ * its whole part and full fractional digit string. The numeric prefix is used
172
+ * and fractional precision is preserved, never truncated (AUD-038).
173
+ */
174
+ function splitAmount(decimalOrMinima) {
175
+ const match = /^([0-9]+(?:\.[0-9]+)?)/.exec(decimalOrMinima.trim());
176
+ const num = match ? match[1] : decimalOrMinima.trim();
177
+ if (!num || !/^[0-9]+(\.[0-9]+)?$/.test(num))
178
+ return { whole: 0n, frac: '' };
179
+ const [whole, frac] = num.split('.');
180
+ return { whole: BigInt(whole), frac: frac ?? '' };
181
+ }
182
+ /**
183
+ * Compare two decimal amounts exactly at a common scale derived from the
184
+ * inputs. Neither side is fixed-truncated, so a claim can never be rounded
185
+ * down into passing (AUD-038).
186
+ */
187
+ export function compareAmounts(a, b) {
188
+ const left = splitAmount(a);
189
+ const right = splitAmount(b);
190
+ if (left.whole < right.whole)
191
+ return -1;
192
+ if (left.whole > right.whole)
193
+ return 1;
194
+ const scale = Math.max(left.frac.length, right.frac.length);
195
+ const leftFrac = BigInt(left.frac.padEnd(scale, '0') || '0');
196
+ const rightFrac = BigInt(right.frac.padEnd(scale, '0') || '0');
197
+ if (leftFrac < rightFrac)
198
+ return -1;
199
+ if (leftFrac > rightFrac)
200
+ return 1;
201
+ return 0;
202
+ }
package/package.json CHANGED
@@ -1,14 +1,19 @@
1
1
  {
2
2
  "name": "@totemsdk/chain-provider",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Unified ChainStateProvider interface for Totem SDK — Hosted, Minima RPC, Composite",
5
- "main": "dist/index.js",
6
- "types": "dist/index.d.ts",
5
+ "main": "dist/cjs/index.js",
6
+ "types": "dist/cjs/index.d.ts",
7
7
  "exports": {
8
8
  ".": {
9
- "types": "./dist/index.d.ts",
10
- "require": "./dist/index.js",
11
- "import": "./dist/index.js"
9
+ "import": {
10
+ "types": "./dist/index.d.ts",
11
+ "default": "./dist/index.js"
12
+ },
13
+ "require": {
14
+ "types": "./dist/cjs/index.d.ts",
15
+ "default": "./dist/cjs/index.js"
16
+ }
12
17
  }
13
18
  },
14
19
  "files": [
@@ -17,8 +22,8 @@
17
22
  "LICENSE"
18
23
  ],
19
24
  "dependencies": {
20
- "@totemsdk/core": "^1.2.9",
21
- "@totemsdk/minima-rpc": "^0.2.0"
25
+ "@totemsdk/minima-rpc": "^0.4.0",
26
+ "@totemsdk/core": "^1.4.0"
22
27
  },
23
28
  "devDependencies": {
24
29
  "@types/jest": "^30.0.0",
@@ -35,7 +40,7 @@
35
40
  },
36
41
  "license": "MIT",
37
42
  "author": "Totem SDK",
38
- "homepage": "https://totem.ing",
43
+ "homepage": "https://docs.totem.ing",
39
44
  "bugs": {
40
45
  "url": "https://github.com/Totem-Edge/totem-sdk/issues"
41
46
  },
@@ -58,8 +63,9 @@
58
63
  "chain-data",
59
64
  "strategy-pattern"
60
65
  ],
66
+ "type": "module",
61
67
  "scripts": {
62
- "build": "tsc",
68
+ "build": "tsc && tsc -p tsconfig.cjs.json && node -e \"require('fs').writeFileSync('dist/cjs/package.json', JSON.stringify({type:'commonjs'})+'\\n')\"",
63
69
  "clean": "rm -rf dist",
64
70
  "test": "jest"
65
71
  }