@spectratools/tx-shared 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,130 @@
1
+ import {
2
+ TxError
3
+ } from "./chunk-6T4D5UCR.js";
4
+
5
+ // src/execute-tx.ts
6
+ async function executeTx(options) {
7
+ const {
8
+ publicClient,
9
+ walletClient,
10
+ account,
11
+ address,
12
+ abi,
13
+ functionName,
14
+ chain,
15
+ args,
16
+ value,
17
+ gasLimit,
18
+ maxFeePerGas,
19
+ nonce,
20
+ dryRun = false
21
+ } = options;
22
+ let estimatedGas;
23
+ try {
24
+ estimatedGas = await publicClient.estimateContractGas({
25
+ account,
26
+ address,
27
+ abi,
28
+ functionName,
29
+ args,
30
+ value
31
+ });
32
+ } catch (error) {
33
+ throw mapError(error, "estimation");
34
+ }
35
+ let simulationResult;
36
+ try {
37
+ const sim = await publicClient.simulateContract({
38
+ account,
39
+ address,
40
+ abi,
41
+ functionName,
42
+ args,
43
+ value
44
+ });
45
+ simulationResult = sim.result;
46
+ } catch (error) {
47
+ throw mapError(error, "simulation");
48
+ }
49
+ if (dryRun) {
50
+ return {
51
+ status: "dry-run",
52
+ estimatedGas,
53
+ simulationResult
54
+ };
55
+ }
56
+ let hash;
57
+ try {
58
+ hash = await walletClient.writeContract({
59
+ account,
60
+ address,
61
+ abi,
62
+ functionName,
63
+ args,
64
+ value,
65
+ chain,
66
+ gas: gasLimit ?? estimatedGas,
67
+ maxFeePerGas,
68
+ nonce
69
+ });
70
+ } catch (error) {
71
+ throw mapError(error, "submit");
72
+ }
73
+ let receipt;
74
+ try {
75
+ receipt = await publicClient.waitForTransactionReceipt({ hash });
76
+ } catch (error) {
77
+ throw mapError(error, "receipt");
78
+ }
79
+ if (receipt.status === "reverted") {
80
+ throw new TxError("TX_REVERTED", `Transaction ${hash} reverted on-chain`);
81
+ }
82
+ return receiptToTxResult(receipt);
83
+ }
84
+ function receiptToTxResult(receipt) {
85
+ return {
86
+ hash: receipt.transactionHash,
87
+ blockNumber: receipt.blockNumber,
88
+ gasUsed: receipt.gasUsed,
89
+ status: receipt.status === "success" ? "success" : "reverted",
90
+ from: receipt.from,
91
+ to: receipt.to,
92
+ effectiveGasPrice: receipt.effectiveGasPrice
93
+ };
94
+ }
95
+ function mapError(error, phase) {
96
+ const msg = errorMessage(error);
97
+ if (matchesInsufficientFunds(msg)) {
98
+ return new TxError("INSUFFICIENT_FUNDS", `Insufficient funds: ${msg}`, error);
99
+ }
100
+ if (matchesNonceConflict(msg)) {
101
+ return new TxError("NONCE_CONFLICT", `Nonce conflict: ${msg}`, error);
102
+ }
103
+ if (phase === "estimation" || phase === "simulation") {
104
+ return new TxError("GAS_ESTIMATION_FAILED", `Gas estimation/simulation failed: ${msg}`, error);
105
+ }
106
+ if (matchesRevert(msg)) {
107
+ return new TxError("TX_REVERTED", `Transaction reverted: ${msg}`, error);
108
+ }
109
+ return new TxError("TX_REVERTED", `Transaction failed (${phase}): ${msg}`, error);
110
+ }
111
+ function errorMessage(error) {
112
+ if (error instanceof Error) return error.message;
113
+ return String(error);
114
+ }
115
+ function matchesInsufficientFunds(msg) {
116
+ const lower = msg.toLowerCase();
117
+ return lower.includes("insufficient funds") || lower.includes("insufficient balance") || lower.includes("sender doesn't have enough funds");
118
+ }
119
+ function matchesNonceConflict(msg) {
120
+ const lower = msg.toLowerCase();
121
+ return lower.includes("nonce too low") || lower.includes("nonce has already been used") || lower.includes("already known") || lower.includes("replacement transaction underpriced");
122
+ }
123
+ function matchesRevert(msg) {
124
+ const lower = msg.toLowerCase();
125
+ return lower.includes("revert") || lower.includes("execution reverted") || lower.includes("transaction failed");
126
+ }
127
+
128
+ export {
129
+ executeTx
130
+ };
@@ -0,0 +1,63 @@
1
+ import { PublicClient, WalletClient, Account, Address, Abi, Chain } from 'viem';
2
+ import { TxResult } from './types.js';
3
+
4
+ /** Options for the {@link executeTx} lifecycle. */
5
+ interface ExecuteTxOptions {
6
+ /** Viem public client used for gas estimation, simulation, and receipt retrieval. */
7
+ publicClient: PublicClient;
8
+ /** Viem wallet client used to submit the transaction. */
9
+ walletClient: WalletClient;
10
+ /** Signer account. */
11
+ account: Account;
12
+ /** Target contract address. */
13
+ address: Address;
14
+ /** Contract ABI (must include the target function). */
15
+ abi: Abi;
16
+ /** Name of the contract function to call. */
17
+ functionName: string;
18
+ /** Optional chain to use for the transaction. */
19
+ chain?: Chain;
20
+ /** Arguments passed to the contract function. */
21
+ args?: unknown[];
22
+ /** Native value (in wei) to send with the transaction. */
23
+ value?: bigint;
24
+ /** Gas limit override. When provided the estimate is still performed but this value is used for submission. */
25
+ gasLimit?: bigint;
26
+ /** Max fee per gas override (EIP-1559). */
27
+ maxFeePerGas?: bigint;
28
+ /** Nonce override. */
29
+ nonce?: number;
30
+ /**
31
+ * When `true` the transaction is simulated but **not** broadcast.
32
+ * Returns a {@link DryRunResult} instead of a {@link TxResult}.
33
+ */
34
+ dryRun?: boolean;
35
+ }
36
+ /** Result returned when `dryRun` is `true`. */
37
+ interface DryRunResult {
38
+ /** Discriminator — always `'dry-run'` for dry-run results. */
39
+ status: 'dry-run';
40
+ /** Estimated gas units for the call. */
41
+ estimatedGas: bigint;
42
+ /** Simulated return value from `simulateContract`. */
43
+ simulationResult: unknown;
44
+ }
45
+ /**
46
+ * Execute a full transaction lifecycle:
47
+ *
48
+ * 1. **Estimate** gas via `publicClient.estimateContractGas`.
49
+ * 2. **Simulate** contract call via `publicClient.simulateContract`.
50
+ * - If `dryRun` is `true`, return a {@link DryRunResult} without broadcasting.
51
+ * 3. **Submit** the transaction via `walletClient.writeContract`.
52
+ * 4. **Wait** for the receipt via `publicClient.waitForTransactionReceipt`.
53
+ * 5. **Normalize** the receipt into a {@link TxResult}.
54
+ *
55
+ * Errors thrown by viem are mapped to structured {@link TxError} codes:
56
+ * - `INSUFFICIENT_FUNDS` — sender lacks balance for value + gas.
57
+ * - `NONCE_CONFLICT` — nonce already used or too low.
58
+ * - `GAS_ESTIMATION_FAILED` — gas estimation or simulation reverted.
59
+ * - `TX_REVERTED` — on-chain revert (includes reason when available).
60
+ */
61
+ declare function executeTx(options: ExecuteTxOptions): Promise<TxResult | DryRunResult>;
62
+
63
+ export { type DryRunResult, type ExecuteTxOptions, executeTx };
@@ -0,0 +1,7 @@
1
+ import {
2
+ executeTx
3
+ } from "./chunk-4XI6TBKX.js";
4
+ import "./chunk-6T4D5UCR.js";
5
+ export {
6
+ executeTx
7
+ };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,33 @@
1
- export { SignerOptions, SignerProvider, TxResult, TxSigner } from './types.js';
1
+ import { TxSigner } from './types.js';
2
+ export { SignerOptions, SignerProvider, TxResult } from './types.js';
2
3
  export { TxError, TxErrorCode, toTxError } from './errors.js';
3
4
  export { abstractMainnet, createAbstractClient } from './chain.js';
5
+ export { DryRunResult, ExecuteTxOptions, executeTx } from './execute-tx.js';
4
6
  import 'viem';
7
+
8
+ /**
9
+ * Create a {@link TxSigner} from a raw private key.
10
+ *
11
+ * @param privateKey - `0x`-prefixed 32-byte hex string.
12
+ * @returns A signer backed by `viem/accounts.privateKeyToAccount`.
13
+ * @throws {TxError} `SIGNER_NOT_CONFIGURED` when the key format is invalid.
14
+ */
15
+ declare function createPrivateKeySigner(privateKey: string): TxSigner;
16
+
17
+ /** Options for {@link createKeystoreSigner}. */
18
+ interface KeystoreSignerOptions {
19
+ /** Path to the V3 keystore JSON file. */
20
+ keystorePath: string;
21
+ /** Password used to decrypt the keystore. */
22
+ keystorePassword: string;
23
+ }
24
+ /**
25
+ * Create a {@link TxSigner} by decrypting a V3 keystore file.
26
+ *
27
+ * Uses `ox` for key derivation (scrypt / pbkdf2) and AES-128-CTR decryption.
28
+ *
29
+ * @throws {TxError} `KEYSTORE_DECRYPT_FAILED` when the file cannot be read, parsed, or decrypted.
30
+ */
31
+ declare function createKeystoreSigner(options: KeystoreSignerOptions): TxSigner;
32
+
33
+ export { type KeystoreSignerOptions, TxSigner, createKeystoreSigner, createPrivateKeySigner };
package/dist/index.js CHANGED
@@ -2,14 +2,66 @@ import {
2
2
  abstractMainnet,
3
3
  createAbstractClient
4
4
  } from "./chunk-P4ACSL6N.js";
5
+ import {
6
+ executeTx
7
+ } from "./chunk-4XI6TBKX.js";
5
8
  import {
6
9
  TxError,
7
10
  toTxError
8
11
  } from "./chunk-6T4D5UCR.js";
9
12
  import "./chunk-6F4PWJZI.js";
13
+
14
+ // src/signers/private-key.ts
15
+ import { privateKeyToAccount } from "viem/accounts";
16
+ var PRIVATE_KEY_REGEX = /^0x[0-9a-fA-F]{64}$/;
17
+ function createPrivateKeySigner(privateKey) {
18
+ if (!PRIVATE_KEY_REGEX.test(privateKey)) {
19
+ throw new TxError(
20
+ "SIGNER_NOT_CONFIGURED",
21
+ "Invalid private key format: expected 0x-prefixed 32-byte hex string"
22
+ );
23
+ }
24
+ const account = privateKeyToAccount(privateKey);
25
+ return { account, address: account.address, provider: "private-key" };
26
+ }
27
+
28
+ // src/signers/keystore.ts
29
+ import { readFileSync } from "fs";
30
+ import { Keystore } from "ox";
31
+ import { privateKeyToAccount as privateKeyToAccount2 } from "viem/accounts";
32
+ function createKeystoreSigner(options) {
33
+ const { keystorePath, keystorePassword } = options;
34
+ let keystoreJson;
35
+ try {
36
+ const raw = readFileSync(keystorePath, "utf-8");
37
+ keystoreJson = JSON.parse(raw);
38
+ } catch (cause) {
39
+ throw new TxError(
40
+ "KEYSTORE_DECRYPT_FAILED",
41
+ `Failed to read keystore file: ${keystorePath}`,
42
+ cause
43
+ );
44
+ }
45
+ let privateKey;
46
+ try {
47
+ const key = Keystore.toKey(keystoreJson, { password: keystorePassword });
48
+ privateKey = Keystore.decrypt(keystoreJson, key);
49
+ } catch (cause) {
50
+ throw new TxError(
51
+ "KEYSTORE_DECRYPT_FAILED",
52
+ `Failed to decrypt keystore: ${cause instanceof Error ? cause.message : String(cause)}`,
53
+ cause
54
+ );
55
+ }
56
+ const account = privateKeyToAccount2(privateKey);
57
+ return { account, address: account.address, provider: "keystore" };
58
+ }
10
59
  export {
11
60
  TxError,
12
61
  abstractMainnet,
13
62
  createAbstractClient,
63
+ createKeystoreSigner,
64
+ createPrivateKeySigner,
65
+ executeTx,
14
66
  toTxError
15
67
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@spectratools/tx-shared",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Shared transaction primitives, signer types, and chain config for spectra tools",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -30,6 +30,10 @@
30
30
  "./chain": {
31
31
  "types": "./dist/chain.d.ts",
32
32
  "default": "./dist/chain.js"
33
+ },
34
+ "./execute-tx": {
35
+ "types": "./dist/execute-tx.d.ts",
36
+ "default": "./dist/execute-tx.js"
33
37
  }
34
38
  },
35
39
  "dependencies": {