@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.
@@ -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.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,11 +1,6 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.CompositeProvider = exports.LookupClientProvider = exports.MinimaRpcProvider = exports.HostedProvider = void 0;
4
- var hosted_js_1 = require("./providers/hosted.js");
5
- Object.defineProperty(exports, "HostedProvider", { enumerable: true, get: function () { return hosted_js_1.HostedProvider; } });
6
- var minima_rpc_js_1 = require("./providers/minima-rpc.js");
7
- Object.defineProperty(exports, "MinimaRpcProvider", { enumerable: true, get: function () { return minima_rpc_js_1.MinimaRpcProvider; } });
8
- var lookup_client_js_1 = require("./providers/lookup-client.js");
9
- Object.defineProperty(exports, "LookupClientProvider", { enumerable: true, get: function () { return lookup_client_js_1.LookupClientProvider; } });
10
- var composite_js_1 = require("./providers/composite.js");
11
- Object.defineProperty(exports, "CompositeProvider", { enumerable: true, get: function () { return composite_js_1.CompositeProvider; } });
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;
@@ -1,4 +1,3 @@
1
- "use strict";
2
1
  /**
3
2
  * LookupClientProvider — ChainStateProvider backed by a @totemsdk/lookup-client instance.
4
3
  *
@@ -33,9 +32,7 @@
33
32
  * );
34
33
  * ```
35
34
  */
36
- Object.defineProperty(exports, "__esModule", { value: true });
37
- exports.LookupClientProvider = void 0;
38
- class LookupClientProvider {
35
+ export class LookupClientProvider {
39
36
  constructor(_client) {
40
37
  this._client = _client;
41
38
  }
@@ -64,4 +61,3 @@ class LookupClientProvider {
64
61
  return this._client.broadcastTxPoW(txpowHex);
65
62
  }
66
63
  }
67
- exports.LookupClientProvider = LookupClientProvider;
@@ -2,16 +2,48 @@
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>;
25
+ /**
26
+ * Current minimum TxPoW work from the tip block's Magic numbers (`magic`
27
+ * command). This is the live target locally mined transactions must meet;
28
+ * using it avoids hardcoding a difficulty that may be harder than the
29
+ * network currently requires (or easier than it has drifted to).
30
+ */
31
+ getMinTxPowWork(): Promise<string | null>;
12
32
  getTip(): Promise<ChainTip>;
13
33
  getToken(tokenId: string): Promise<TokenInfo>;
14
34
  searchTokens(query: TokenSearchQuery): Promise<TokenInfo[]>;
15
35
  getTokensByCreator(address: string): Promise<TokenInfo[]>;
36
+ /**
37
+ * Submit a raw transaction + witness via the node's explicit-mine path.
38
+ *
39
+ * `sendtransaction` only adds a pre-built TxPoW to the mempool; a TxPoW built
40
+ * outside the node has a placeholder header (block number 0, block difficulty
41
+ * MAX_HASH), which the node's block builder does not reliably promote. The
42
+ * node's own `txnmine` builds the header with the real tip fields and mines
43
+ * it. We then post that mined TxPoW with `sendtransaction`.
44
+ *
45
+ * TxnRow wire format (Java/C++): MiniString(id) || Transaction || Witness.
46
+ */
47
+ submitTransaction(txBytes: Uint8Array, witnessBytes: Uint8Array, id?: string): Promise<BroadcastResult>;
16
48
  broadcastTxPoW(txpowHex: string): Promise<BroadcastResult>;
17
49
  }
@@ -1,10 +1,8 @@
1
- "use strict";
2
1
  /**
3
2
  * MinimaRpcProvider — thin wrapper over @totemsdk/minima-rpc.
4
3
  */
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.MinimaRpcProvider = void 0;
7
- class MinimaRpcProvider {
4
+ import { depositAddressFor, evaluateDeposit, notFoundResult } from '../verify-deposit.js';
5
+ export class MinimaRpcProvider {
8
6
  constructor(client) {
9
7
  this.client = client;
10
8
  }
@@ -20,6 +18,19 @@ class MinimaRpcProvider {
20
18
  return result;
21
19
  }
22
20
  async getCoin(coinId) {
21
+ // `coins` only returns wallet-relevant coins, so it never sees coins locked
22
+ // to an app/channel script. `coinexport` is the chain-level primitive and is
23
+ // the only reliable way to resolve an arbitrary coinid (see verifyDeposit).
24
+ try {
25
+ const exported = await this.client.coinExport(coinId);
26
+ const coin = exported?.coinproof?.coin;
27
+ if (coin) {
28
+ return { ...coin, spent: coin.spent === true };
29
+ }
30
+ }
31
+ catch {
32
+ // fall through to the wallet query
33
+ }
23
34
  try {
24
35
  const coins = await this.getCoins({ coinId });
25
36
  return coins[0] ?? null;
@@ -28,9 +39,62 @@ class MinimaRpcProvider {
28
39
  return null;
29
40
  }
30
41
  }
42
+ /**
43
+ * Authoritative live check via `coinexport` (the coinproof endpoint): returns
44
+ * found/unspent/owned/token/amount + the full coin proof. `coincheck` on
45
+ * totem-node wants a full proof payload rather than a coinid, so coinexport
46
+ * is the canonical primitive (#3).
47
+ */
48
+ async verifyDeposit(params) {
49
+ try {
50
+ const exported = await this.client.coinExport(params.coinId);
51
+ const coin = exported?.coinproof?.coin;
52
+ const spent = coin?.spent === true;
53
+ if (!coin) {
54
+ return notFoundResult(`coin ${params.coinId} not found on chain`);
55
+ }
56
+ return evaluateDeposit(coin, spent, params);
57
+ }
58
+ catch (error) {
59
+ return {
60
+ valid: false,
61
+ exists: false,
62
+ unspent: false,
63
+ confirmed: false,
64
+ ownedByOwner: false,
65
+ tokenMatches: false,
66
+ amountSufficient: false,
67
+ reason: 'unable to reach chain provider',
68
+ error,
69
+ };
70
+ }
71
+ }
72
+ depositAddressFor(lp, opts) {
73
+ return depositAddressFor(lp, opts);
74
+ }
75
+ /** MMR root at tip — the anchor peers verify offline proofs against. */
76
+ async getMmrRoot() {
77
+ const info = await this.client.megammr();
78
+ return info?.hash ?? null;
79
+ }
31
80
  async getProof(coinId) {
32
81
  return this.client.mmrProof(coinId);
33
82
  }
83
+ /**
84
+ * Current minimum TxPoW work from the tip block's Magic numbers (`magic`
85
+ * command). This is the live target locally mined transactions must meet;
86
+ * using it avoids hardcoding a difficulty that may be harder than the
87
+ * network currently requires (or easier than it has drifted to).
88
+ */
89
+ async getMinTxPowWork() {
90
+ try {
91
+ const info = await this.client.magic();
92
+ return info?.lastblock?.currentmintxpowwork ?? null;
93
+ }
94
+ catch {
95
+ return null;
96
+ }
97
+ }
34
98
  async getTip() {
35
99
  return this.client.getTip();
36
100
  }
@@ -67,13 +131,58 @@ class MinimaRpcProvider {
67
131
  async getTokensByCreator(address) {
68
132
  return this.searchTokens({ creatorAddress: address });
69
133
  }
134
+ /**
135
+ * Submit a raw transaction + witness via the node's explicit-mine path.
136
+ *
137
+ * `sendtransaction` only adds a pre-built TxPoW to the mempool; a TxPoW built
138
+ * outside the node has a placeholder header (block number 0, block difficulty
139
+ * MAX_HASH), which the node's block builder does not reliably promote. The
140
+ * node's own `txnmine` builds the header with the real tip fields and mines
141
+ * it. We then post that mined TxPoW with `sendtransaction`.
142
+ *
143
+ * TxnRow wire format (Java/C++): MiniString(id) || Transaction || Witness.
144
+ */
145
+ async submitTransaction(txBytes, witnessBytes, id = `omnia-${Date.now()}`) {
146
+ try {
147
+ const idBytes = new TextEncoder().encode(id);
148
+ const len = idBytes.length;
149
+ const prefix = new Uint8Array([
150
+ (len >>> 24) & 0xff,
151
+ (len >>> 16) & 0xff,
152
+ (len >>> 8) & 0xff,
153
+ len & 0xff,
154
+ ]);
155
+ const row = Buffer.concat([
156
+ Buffer.from(prefix),
157
+ Buffer.from(idBytes),
158
+ Buffer.from(txBytes),
159
+ Buffer.from(witnessBytes),
160
+ ]);
161
+ const mined = await this.client.txnMine({ data: Buffer.from(row).toString('hex') });
162
+ if (!mined?.data) {
163
+ return { success: false, message: 'txnmine returned no data' };
164
+ }
165
+ const posted = await this.client.sendTransaction(mined.data);
166
+ return {
167
+ success: true,
168
+ txpowid: mined.txpowid ?? posted?.txpowid,
169
+ message: 'submitted via txnmine + sendtransaction',
170
+ };
171
+ }
172
+ catch (e) {
173
+ return { success: false, message: String(e) };
174
+ }
175
+ }
70
176
  async broadcastTxPoW(txpowHex) {
71
177
  try {
72
- const result = await this.client.txnMinePost(txpowHex);
178
+ // `sendtransaction` submits a pre-mined TxPoW to the mempool where the
179
+ // node mines it into a block. `txnminepost` only posts the TxPoW (via the
180
+ // peer NIO path) and does not get it mined.
181
+ const result = await this.client.sendTransaction(txpowHex);
73
182
  return {
74
183
  success: true,
75
184
  txpowid: result?.txpowid,
76
- message: 'broadcast via MinimaRpc txnminepost',
185
+ message: 'broadcast via MinimaRpc sendtransaction',
77
186
  };
78
187
  }
79
188
  catch (e) {
@@ -81,4 +190,3 @@ class MinimaRpcProvider {
81
190
  }
82
191
  }
83
192
  }
84
- exports.MinimaRpcProvider = MinimaRpcProvider;
@@ -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,94 @@
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 { createMinimaRpcClient } from '@totemsdk/minima-rpc';
15
+ import { HostedProvider } from './providers/hosted.js';
16
+ import { MinimaRpcProvider } from './providers/minima-rpc.js';
17
+ import { CompositeProvider } from './providers/composite.js';
18
+ const DEFAULT_RPC_PORT = 9005;
19
+ /** Parse `http(s)://host:port` into the minima-rpc client config shape. */
20
+ export function parseMinimaRpcUrl(url) {
21
+ let parsed;
22
+ try {
23
+ parsed = new URL(url);
24
+ }
25
+ catch {
26
+ throw new Error(`Invalid Minima RPC URL: ${url}`);
27
+ }
28
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
29
+ throw new Error('Minima RPC URL must use http: (loopback) or https:');
30
+ }
31
+ const ssl = parsed.protocol === 'https:';
32
+ const port = parsed.port ? Number(parsed.port) : ssl ? 443 : DEFAULT_RPC_PORT;
33
+ if (!Number.isInteger(port) || port <= 0 || port > 65535) {
34
+ throw new Error(`Invalid Minima RPC port in URL: ${url}`);
35
+ }
36
+ return { host: parsed.hostname, port, ssl };
37
+ }
38
+ function isLoopbackHost(hostname) {
39
+ return hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '::1' || hostname === '[::1]';
40
+ }
41
+ /**
42
+ * Consent guard (RFC-013 §11): HTTPS is required for remote hosts; plain `http`
43
+ * is permitted only for loopback. Never ships a build-time localhost bypass.
44
+ */
45
+ export function assertConsentedNodeUrl(url) {
46
+ const parsed = new URL(url);
47
+ if (parsed.protocol === 'https:')
48
+ return;
49
+ if (parsed.protocol === 'http:' && isLoopbackHost(parsed.hostname))
50
+ return;
51
+ throw new Error('Self-hosted node URL must use HTTPS. Plain http is allowed only for localhost/127.0.0.1/::1.');
52
+ }
53
+ function createNodeProvider(config) {
54
+ if (!config.minimaRpcUrl) {
55
+ throw new Error('minima-rpc mode requires minimaRpcUrl');
56
+ }
57
+ const { host, port, ssl } = parseMinimaRpcUrl(config.minimaRpcUrl);
58
+ const client = createMinimaRpcClient({
59
+ host,
60
+ port,
61
+ ssl,
62
+ ...(config.minimaRpcUser ? { username: config.minimaRpcUser } : {}),
63
+ ...(config.minimaRpcPass ? { password: config.minimaRpcPass } : {}),
64
+ });
65
+ return new MinimaRpcProvider(client);
66
+ }
67
+ /**
68
+ * Resolve a {@link ChainStateProvider} from the persisted config.
69
+ *
70
+ * - `axia` → the hosted relay (default).
71
+ * - `minima-rpc` → the user's own node.
72
+ * - `composite` → node first, hosted fallback (unless `fallbackToAxia === false`).
73
+ */
74
+ export function resolveChainProvider(config, options) {
75
+ const hosted = options.hostedProvider ?? new HostedProvider(options.hosted);
76
+ if (config.mode === 'axia') {
77
+ return hosted;
78
+ }
79
+ if (!config.minimaRpcUrl) {
80
+ throw new Error(`chain provider mode "${config.mode}" requires minimaRpcUrl`);
81
+ }
82
+ (options.validateUrl ?? assertConsentedNodeUrl)(config.minimaRpcUrl);
83
+ const node = options.createMinimaProvider
84
+ ? options.createMinimaProvider(config)
85
+ : createNodeProvider(config);
86
+ if (config.mode === 'minima-rpc' || config.fallbackToAxia === false) {
87
+ return node;
88
+ }
89
+ return new CompositeProvider(node, hosted, options.onFallback);
90
+ }
91
+ /** True when the config routes reads/broadcast away from the hosted relay. */
92
+ export function isSelfHosted(config) {
93
+ return config.mode === 'minima-rpc' || config.mode === 'composite';
94
+ }