@hardkas/bridge-local 0.4.0-alpha

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Javier Rodriguez
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,74 @@
1
+ import { NetworkId } from '@hardkas/core';
2
+ import { TxPlan, Utxo } from '@hardkas/tx-builder';
3
+ import { LoadedHardkasConfig } from '@hardkas/config';
4
+
5
+ interface BridgeEntryPayload {
6
+ readonly marker: string;
7
+ readonly targetEvmAddress: string;
8
+ readonly amountSompi: bigint;
9
+ readonly networkId: NetworkId;
10
+ readonly nonce?: number;
11
+ }
12
+ /**
13
+ * Deterministically serializes a bridge entry payload to hex.
14
+ */
15
+ declare function serializeBridgePayload(payload: BridgeEntryPayload): string;
16
+ declare function deserializeBridgePayload(hex: string): BridgeEntryPayload;
17
+
18
+ interface MiningResult {
19
+ readonly nonce: number;
20
+ readonly hash: string;
21
+ readonly attempts: number;
22
+ }
23
+ /**
24
+ * Simulates prefix mining by incrementing a nonce until the deterministic hash
25
+ * of the payload matches the desired prefix.
26
+ */
27
+ declare function simulatePrefixMining(payloadBase: Omit<BridgeEntryPayload, "nonce">, prefix: string, options?: {
28
+ initialNonce?: number;
29
+ maxAttempts?: number;
30
+ timeoutMs?: number;
31
+ }): MiningResult;
32
+
33
+ interface BridgePlanRequest {
34
+ readonly fromAddress: string;
35
+ readonly targetEvmAddress: string;
36
+ readonly amountSompi: bigint;
37
+ readonly networkId: NetworkId;
38
+ readonly availableUtxos: readonly Utxo[];
39
+ }
40
+ interface BridgePlan extends TxPlan {
41
+ readonly bridgePayload: BridgeEntryPayload;
42
+ readonly serializedPayload: string;
43
+ }
44
+ declare function planBridgeEntry(request: BridgePlanRequest): BridgePlan;
45
+
46
+ type BridgeLocalResolutionSource = "explicit" | "named-session" | "active-session";
47
+ interface ResolvedBridgeLocalContext {
48
+ source: BridgeLocalResolutionSource;
49
+ sessionName?: string;
50
+ l1: {
51
+ walletName: string;
52
+ address: string;
53
+ };
54
+ l2: {
55
+ accountName?: string;
56
+ address: `0x${string}`;
57
+ };
58
+ bridgeMode: "local-simulated";
59
+ }
60
+ interface ResolveBridgeOptions {
61
+ config: LoadedHardkasConfig;
62
+ sessionName?: string;
63
+ from?: string;
64
+ toIgra?: string;
65
+ }
66
+ /**
67
+ * Resolves the L1/L2 bridge context with the following priority:
68
+ * 1. Explicit flags (--from, --to-igra)
69
+ * 2. Named session (--session)
70
+ * 3. Active session
71
+ */
72
+ declare function resolveBridgeLocalContext(options: ResolveBridgeOptions): Promise<ResolvedBridgeLocalContext>;
73
+
74
+ export { type BridgeEntryPayload, type BridgeLocalResolutionSource, type BridgePlan, type BridgePlanRequest, type MiningResult, type ResolveBridgeOptions, type ResolvedBridgeLocalContext, deserializeBridgePayload, planBridgeEntry, resolveBridgeLocalContext, serializeBridgePayload, simulatePrefixMining };
package/dist/index.js ADDED
@@ -0,0 +1,132 @@
1
+ // src/payload.ts
2
+ function serializeBridgePayload(payload) {
3
+ const markerHex = Buffer.from(payload.marker.padEnd(4).slice(0, 4)).toString("hex");
4
+ const addrHex = payload.targetEvmAddress.replace("0x", "").toLowerCase().padStart(40, "0");
5
+ const amountHex = payload.amountSompi.toString(16).padStart(16, "0");
6
+ const networkHex = Buffer.from(payload.networkId.padEnd(2).slice(0, 2)).toString("hex");
7
+ const nonceHex = (payload.nonce ?? 0).toString(16).padStart(8, "0");
8
+ return `${markerHex}${addrHex}${amountHex}${networkHex}${nonceHex}`;
9
+ }
10
+ function deserializeBridgePayload(hex) {
11
+ const marker = Buffer.from(hex.slice(0, 8), "hex").toString().trim();
12
+ const targetEvmAddress = `0x${hex.slice(8, 48)}`;
13
+ const amountSompi = BigInt(`0x${hex.slice(48, 64)}`);
14
+ const networkId = Buffer.from(hex.slice(64, 68), "hex").toString().trim();
15
+ const nonce = parseInt(hex.slice(68, 76), 16);
16
+ return { marker, targetEvmAddress, amountSompi, networkId, nonce };
17
+ }
18
+
19
+ // src/prefix-miner.ts
20
+ import { calculateContentHash } from "@hardkas/artifacts";
21
+ function simulatePrefixMining(payloadBase, prefix, options = {}) {
22
+ const initialNonce = options.initialNonce ?? 0;
23
+ const maxAttempts = options.maxAttempts ?? 1e5;
24
+ const timeoutMs = options.timeoutMs ?? 5e3;
25
+ const startTime = Date.now();
26
+ let nonce = initialNonce;
27
+ let attempts = 0;
28
+ while (attempts < maxAttempts) {
29
+ if (Date.now() - startTime > timeoutMs) {
30
+ throw new Error(`Mining simulation timed out after ${timeoutMs}ms`);
31
+ }
32
+ const payload = { ...payloadBase, nonce };
33
+ const serialized = serializeBridgePayload(payload);
34
+ const hash = calculateContentHash({ payload: serialized });
35
+ if (hash.startsWith(prefix)) {
36
+ return { nonce, hash, attempts: attempts + 1 };
37
+ }
38
+ nonce++;
39
+ attempts++;
40
+ }
41
+ throw new Error(`Failed to find prefix "${prefix}" after ${attempts} attempts.`);
42
+ }
43
+
44
+ // src/planner.ts
45
+ import { buildPaymentPlan } from "@hardkas/tx-builder";
46
+ function planBridgeEntry(request) {
47
+ const bridgePayload = {
48
+ marker: "IGRA",
49
+ targetEvmAddress: request.targetEvmAddress,
50
+ amountSompi: request.amountSompi,
51
+ networkId: request.networkId
52
+ };
53
+ const serializedPayload = serializeBridgePayload(bridgePayload);
54
+ const payloadBytes = serializedPayload.length / 2;
55
+ const txPlan = buildPaymentPlan({
56
+ fromAddress: request.fromAddress,
57
+ outputs: [
58
+ // In a real bridge, this might be a specific bridge multisig or script
59
+ { address: request.fromAddress, amountSompi: request.amountSompi }
60
+ ],
61
+ availableUtxos: request.availableUtxos,
62
+ feeRateSompiPerMass: 1n,
63
+ payloadBytes
64
+ });
65
+ return {
66
+ ...txPlan,
67
+ bridgePayload,
68
+ serializedPayload
69
+ };
70
+ }
71
+
72
+ // src/session-resolver.ts
73
+ import { getActiveSession, loadSessionStore } from "@hardkas/sessions";
74
+ import { resolveHardkasAccountAddress, listHardkasAccounts } from "@hardkas/accounts";
75
+ async function resolveBridgeLocalContext(options) {
76
+ const { config, sessionName, from, toIgra } = options;
77
+ if (from && toIgra) {
78
+ const l1Address = resolveHardkasAccountAddress(from, config.config);
79
+ return {
80
+ source: "explicit",
81
+ l1: { walletName: from, address: l1Address },
82
+ l2: { address: toIgra.startsWith("0x") ? toIgra : `0x${toIgra}` },
83
+ bridgeMode: "local-simulated"
84
+ };
85
+ }
86
+ if (sessionName) {
87
+ const store = loadSessionStore();
88
+ const session = store.sessions[sessionName];
89
+ if (!session) {
90
+ throw new Error(`Session "${sessionName}" not found.`);
91
+ }
92
+ return validateAndFormatSession(session, "named-session", config);
93
+ }
94
+ const activeSession = getActiveSession();
95
+ if (activeSession) {
96
+ return validateAndFormatSession(activeSession, "active-session", config);
97
+ }
98
+ throw new Error(
99
+ "No bridge context resolved.\n\nProvide one of:\n hardkas bridge local plan --amount 100 --session <name>\n hardkas bridge local plan --amount 100 --from <wallet> --to-igra <0x...>\n hardkas session use <name>"
100
+ );
101
+ }
102
+ function validateAndFormatSession(session, source, config) {
103
+ if (session.bridge.mode !== "local-simulated") {
104
+ throw new Error(`Session "${session.name}" has bridge mode "${session.bridge.mode}". Only "local-simulated" is supported in this command.`);
105
+ }
106
+ const accounts = listHardkasAccounts(config.config);
107
+ const l1Found = accounts.find((a) => a.name === session.l1.wallet);
108
+ const l2Found = accounts.find((a) => a.name === session.l2.account);
109
+ if (!l1Found) {
110
+ throw new Error(`Session "${session.name}" refers to missing L1 wallet "${session.l1.wallet}".`);
111
+ }
112
+ return {
113
+ source,
114
+ sessionName: session.name,
115
+ l1: {
116
+ walletName: session.l1.wallet,
117
+ address: l1Found.address || session.l1.address || ""
118
+ },
119
+ l2: {
120
+ accountName: session.l2.account,
121
+ address: session.l2.address || ""
122
+ },
123
+ bridgeMode: "local-simulated"
124
+ };
125
+ }
126
+ export {
127
+ deserializeBridgePayload,
128
+ planBridgeEntry,
129
+ resolveBridgeLocalContext,
130
+ serializeBridgePayload,
131
+ simulatePrefixMining
132
+ };
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "@hardkas/bridge-local",
3
+ "version": "0.4.0-alpha",
4
+ "type": "module",
5
+ "main": "./dist/index.js",
6
+ "types": "./dist/index.d.ts",
7
+ "exports": {
8
+ ".": "./dist/index.js"
9
+ },
10
+ "dependencies": {
11
+ "@hardkas/accounts": "0.4.0-alpha",
12
+ "@hardkas/core": "0.4.0-alpha",
13
+ "@hardkas/artifacts": "0.4.0-alpha",
14
+ "@hardkas/sessions": "0.4.0-alpha",
15
+ "@hardkas/tx-builder": "0.4.0-alpha",
16
+ "@hardkas/config": "0.4.0-alpha"
17
+ },
18
+ "devDependencies": {
19
+ "tsup": "^8.3.5",
20
+ "typescript": "^5.7.2",
21
+ "vitest": "^2.1.8"
22
+ },
23
+ "license": "MIT",
24
+ "author": "Javier Rodriguez",
25
+ "files": [
26
+ "dist",
27
+ "README.md"
28
+ ],
29
+ "scripts": {
30
+ "build": "tsup src/index.ts --format esm --dts --clean",
31
+ "test": "vitest run --passWithNoTests",
32
+ "typecheck": "tsc --noEmit"
33
+ }
34
+ }