@fastxyz/allset-sdk 0.1.12 → 1.0.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.
Files changed (44) hide show
  1. package/README.md +339 -266
  2. package/dist/index.d.ts +658 -5
  3. package/dist/index.js +927 -7
  4. package/package.json +21 -47
  5. package/dist/browser/index.d.ts +0 -2
  6. package/dist/browser/index.d.ts.map +0 -1
  7. package/dist/browser/index.js +0 -1
  8. package/dist/core/address.d.ts +0 -5
  9. package/dist/core/address.d.ts.map +0 -1
  10. package/dist/core/address.js +0 -29
  11. package/dist/core/deposit.d.ts +0 -59
  12. package/dist/core/deposit.d.ts.map +0 -1
  13. package/dist/core/deposit.js +0 -92
  14. package/dist/core/index.d.ts +0 -6
  15. package/dist/core/index.d.ts.map +0 -1
  16. package/dist/core/index.js +0 -3
  17. package/dist/default-config.d.ts +0 -78
  18. package/dist/default-config.d.ts.map +0 -1
  19. package/dist/default-config.js +0 -78
  20. package/dist/index.d.ts.map +0 -1
  21. package/dist/intents.d.ts +0 -94
  22. package/dist/intents.d.ts.map +0 -1
  23. package/dist/intents.js +0 -119
  24. package/dist/node/bridge.d.ts +0 -38
  25. package/dist/node/bridge.d.ts.map +0 -1
  26. package/dist/node/bridge.js +0 -519
  27. package/dist/node/config.d.ts +0 -45
  28. package/dist/node/config.d.ts.map +0 -1
  29. package/dist/node/config.js +0 -48
  30. package/dist/node/eip7702.d.ts +0 -54
  31. package/dist/node/eip7702.d.ts.map +0 -1
  32. package/dist/node/eip7702.js +0 -275
  33. package/dist/node/evm-executor.d.ts +0 -130
  34. package/dist/node/evm-executor.d.ts.map +0 -1
  35. package/dist/node/evm-executor.js +0 -160
  36. package/dist/node/index.d.ts +0 -15
  37. package/dist/node/index.d.ts.map +0 -1
  38. package/dist/node/index.js +0 -17
  39. package/dist/node/provider.d.ts +0 -162
  40. package/dist/node/provider.d.ts.map +0 -1
  41. package/dist/node/provider.js +0 -272
  42. package/dist/node/types.d.ts +0 -110
  43. package/dist/node/types.d.ts.map +0 -1
  44. package/dist/node/types.js +0 -4
@@ -1,45 +0,0 @@
1
- /**
2
- * config.ts — Embedded network configuration accessors
3
- */
4
- export interface TokenConfig {
5
- evmAddress: string;
6
- fastTokenId: string;
7
- decimals: number;
8
- }
9
- export interface ChainConfig {
10
- chainId: number;
11
- bridgeContract: string;
12
- fastBridgeAddress: string;
13
- relayerUrl: string;
14
- tokens: Record<string, TokenConfig>;
15
- }
16
- export interface NetworkConfig {
17
- crossSignUrl: string;
18
- chains: Record<string, ChainConfig>;
19
- }
20
- export interface AllNetworksConfig {
21
- testnet: NetworkConfig;
22
- mainnet: NetworkConfig;
23
- }
24
- /**
25
- * Load the networks configuration.
26
- * Caches a clone of the embedded default config after first load.
27
- */
28
- export declare function loadNetworksConfig(): AllNetworksConfig;
29
- /**
30
- * Get configuration for a specific network (testnet or mainnet).
31
- */
32
- export declare function getNetworkConfig(network?: 'testnet' | 'mainnet'): NetworkConfig;
33
- /**
34
- * Get configuration for a specific chain within a network.
35
- */
36
- export declare function getChainConfig(chain: string, network?: 'testnet' | 'mainnet'): ChainConfig | null;
37
- /**
38
- * Get token configuration for a chain.
39
- */
40
- export declare function getTokenConfig(chain: string, token: string, network?: 'testnet' | 'mainnet'): TokenConfig | null;
41
- /**
42
- * Clear the cached config (useful for testing).
43
- */
44
- export declare function clearConfigCache(): void;
45
- //# sourceMappingURL=config.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/node/config.ts"],"names":[],"mappings":"AAAA;;GAEG;AAQH,MAAM,WAAW,WAAW;IAC1B,UAAU,EAAE,MAAM,CAAC;IACnB,WAAW,EAAE,MAAM,CAAC;IACpB,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,WAAW;IAC1B,OAAO,EAAE,MAAM,CAAC;IAChB,cAAc,EAAE,MAAM,CAAC;IACvB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,UAAU,EAAE,MAAM,CAAC;IACnB,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC;CACrC;AAED,MAAM,WAAW,aAAa;IAC5B,YAAY,EAAE,MAAM,CAAC;IACrB,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC;CACrC;AAED,MAAM,WAAW,iBAAiB;IAChC,OAAO,EAAE,aAAa,CAAC;IACvB,OAAO,EAAE,aAAa,CAAC;CACxB;AAQD;;;GAGG;AACH,wBAAgB,kBAAkB,IAAI,iBAAiB,CAOtD;AAED;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,GAAE,SAAS,GAAG,SAAqB,GAAG,aAAa,CAG1F;AAED;;GAEG;AACH,wBAAgB,cAAc,CAC5B,KAAK,EAAE,MAAM,EACb,OAAO,GAAE,SAAS,GAAG,SAAqB,GACzC,WAAW,GAAG,IAAI,CAGpB;AAED;;GAEG;AACH,wBAAgB,cAAc,CAC5B,KAAK,EAAE,MAAM,EACb,KAAK,EAAE,MAAM,EACb,OAAO,GAAE,SAAS,GAAG,SAAqB,GACzC,WAAW,GAAG,IAAI,CAIpB;AAED;;GAEG;AACH,wBAAgB,gBAAgB,IAAI,IAAI,CAEvC"}
@@ -1,48 +0,0 @@
1
- /**
2
- * config.ts — Embedded network configuration accessors
3
- */
4
- import { DEFAULT_NETWORKS_CONFIG } from '../default-config.js';
5
- // ---------------------------------------------------------------------------
6
- // Config Loading
7
- // ---------------------------------------------------------------------------
8
- let cachedConfig = null;
9
- /**
10
- * Load the networks configuration.
11
- * Caches a clone of the embedded default config after first load.
12
- */
13
- export function loadNetworksConfig() {
14
- if (cachedConfig) {
15
- return cachedConfig;
16
- }
17
- cachedConfig = structuredClone(DEFAULT_NETWORKS_CONFIG);
18
- return cachedConfig;
19
- }
20
- /**
21
- * Get configuration for a specific network (testnet or mainnet).
22
- */
23
- export function getNetworkConfig(network = 'testnet') {
24
- const config = loadNetworksConfig();
25
- return config[network];
26
- }
27
- /**
28
- * Get configuration for a specific chain within a network.
29
- */
30
- export function getChainConfig(chain, network = 'testnet') {
31
- const networkConfig = getNetworkConfig(network);
32
- return networkConfig.chains[chain] ?? null;
33
- }
34
- /**
35
- * Get token configuration for a chain.
36
- */
37
- export function getTokenConfig(chain, token, network = 'testnet') {
38
- const chainConfig = getChainConfig(chain, network);
39
- if (!chainConfig)
40
- return null;
41
- return chainConfig.tokens[token] ?? chainConfig.tokens[token.toUpperCase()] ?? null;
42
- }
43
- /**
44
- * Clear the cached config (useful for testing).
45
- */
46
- export function clearConfigCache() {
47
- cachedConfig = null;
48
- }
@@ -1,54 +0,0 @@
1
- /**
2
- * eip7702.ts — EIP-7702 smartDeposit via AllSet Portal relay
3
- *
4
- * Flow:
5
- * 1. Check ERC-20 balance; throw InsufficientBalanceError if < amount
6
- * 2. POST /userop/prepare → backend assembles UserOp + paymasterData (3 retries)
7
- * 3. Pin delegate address against TRUSTED_DELEGATES allowlist
8
- * 4. Sign EIP-7702 authorization (re-delegate EOA to v0.8 impl)
9
- * 5. Sign UserOperation (EIP-712, v0.8)
10
- * 6. POST /userop/submit → backend calls Pimlico eth_sendUserOperation
11
- *
12
- * Private key never leaves the SDK.
13
- * Pimlico API key never touches the SDK.
14
- * Gas is paid in USDC via ERC-20 Paymaster.
15
- * Chain is inferred from rpcUrl (backend calls eth_chainId) — no hardcoded chain list.
16
- */
17
- import { type Address, type Hash, type Hex } from 'viem';
18
- export interface SmartDepositParams {
19
- /**
20
- * EOA private key — stays local, never sent to backend.
21
- * The EOA should be quiescent during this call: do not send other
22
- * transactions from this key concurrently. EIP-7702 authorization
23
- * signing binds to the account nonce, and a concurrent tx from
24
- * another process will silently invalidate the delegation.
25
- */
26
- privateKey: Hex;
27
- /** EVM JSON-RPC URL — used for balance check and forwarded to backend for chainId detection */
28
- rpcUrl: string;
29
- /** AllSet Portal backend base URL, e.g. https://api.allset.xyz */
30
- allsetApiUrl: string;
31
- /** ERC-20 token to deposit (e.g. USDC on Base) */
32
- tokenAddress: Address;
33
- /** Exact token amount to deposit (raw, with decimals); throws if balance is insufficient */
34
- amount: bigint;
35
- /** AllSet bridge contract address */
36
- bridgeAddress: Address;
37
- /** Encoded bridge.deposit(...) calldata from encodeDepositCalldata() */
38
- depositCalldata: Hex;
39
- /** Per-request HTTP timeout in ms for backend POSTs (default: 60000) */
40
- requestTimeoutMs?: number;
41
- }
42
- export interface SmartDepositResult {
43
- txHash: Hash;
44
- userOpHash: Hash;
45
- userAddress: Address;
46
- }
47
- export declare class InsufficientBalanceError extends Error {
48
- readonly balance: bigint;
49
- readonly required: bigint;
50
- readonly tokenAddress: Address;
51
- constructor(balance: bigint, required: bigint, tokenAddress: Address);
52
- }
53
- export declare function smartDeposit(params: SmartDepositParams): Promise<SmartDepositResult>;
54
- //# sourceMappingURL=eip7702.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"eip7702.d.ts","sourceRoot":"","sources":["../../src/node/eip7702.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,EAML,KAAK,OAAO,EACZ,KAAK,IAAI,EACT,KAAK,GAAG,EACT,MAAM,MAAM,CAAC;AA4Dd,MAAM,WAAW,kBAAkB;IACjC;;;;;;OAMG;IACH,UAAU,EAAE,GAAG,CAAC;IAChB,+FAA+F;IAC/F,MAAM,EAAE,MAAM,CAAC;IACf,kEAAkE;IAClE,YAAY,EAAE,MAAM,CAAC;IACrB,kDAAkD;IAClD,YAAY,EAAE,OAAO,CAAC;IACtB,4FAA4F;IAC5F,MAAM,EAAE,MAAM,CAAC;IACf,qCAAqC;IACrC,aAAa,EAAE,OAAO,CAAC;IACvB,wEAAwE;IACxE,eAAe,EAAE,GAAG,CAAC;IACrB,wEAAwE;IACxE,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC3B;AAED,MAAM,WAAW,kBAAkB;IACjC,MAAM,EAAE,IAAI,CAAC;IACb,UAAU,EAAE,IAAI,CAAC;IACjB,WAAW,EAAE,OAAO,CAAC;CACtB;AAED,qBAAa,wBAAyB,SAAQ,KAAK;aAE/B,OAAO,EAAE,MAAM;aACf,QAAQ,EAAE,MAAM;aAChB,YAAY,EAAE,OAAO;gBAFrB,OAAO,EAAE,MAAM,EACf,QAAQ,EAAE,MAAM,EAChB,YAAY,EAAE,OAAO;CAOxC;AA6HD,wBAAsB,YAAY,CAAC,MAAM,EAAE,kBAAkB,GAAG,OAAO,CAAC,kBAAkB,CAAC,CA2K1F"}
@@ -1,275 +0,0 @@
1
- /**
2
- * eip7702.ts — EIP-7702 smartDeposit via AllSet Portal relay
3
- *
4
- * Flow:
5
- * 1. Check ERC-20 balance; throw InsufficientBalanceError if < amount
6
- * 2. POST /userop/prepare → backend assembles UserOp + paymasterData (3 retries)
7
- * 3. Pin delegate address against TRUSTED_DELEGATES allowlist
8
- * 4. Sign EIP-7702 authorization (re-delegate EOA to v0.8 impl)
9
- * 5. Sign UserOperation (EIP-712, v0.8)
10
- * 6. POST /userop/submit → backend calls Pimlico eth_sendUserOperation
11
- *
12
- * Private key never leaves the SDK.
13
- * Pimlico API key never touches the SDK.
14
- * Gas is paid in USDC via ERC-20 Paymaster.
15
- * Chain is inferred from rpcUrl (backend calls eth_chainId) — no hardcoded chain list.
16
- */
17
- import { createPublicClient, encodeAbiParameters, http, keccak256, parseAbi, } from 'viem';
18
- import { privateKeyToAccount } from 'viem/accounts';
19
- import { getUserOperationTypedData } from 'viem/account-abstraction';
20
- const ENTRY_POINT_V08 = '0x4337084D9E255Ff0702461CF8895CE9E3b5Ff108';
21
- /**
22
- * Allowlist of trusted EIP-7702 delegate addresses (lowercase).
23
- * smartDeposit will throw if the backend returns a delegate not in this set,
24
- * preventing a compromised backend from delegating EOAs to a malicious contract.
25
- */
26
- const TRUSTED_DELEGATES = new Set([
27
- '0xe6cae83bde06e4c305530e199d7217f42808555b', // Simple7702Account v0.8
28
- ]);
29
- const ERC20_BALANCEOF_ABI = parseAbi([
30
- 'function balanceOf(address account) view returns (uint256)',
31
- ]);
32
- /**
33
- * Encode a number/bigint as an even-length 0x-prefixed hex string.
34
- * Some strict bundler parsers expect byte-aligned hex — pad to even length.
35
- */
36
- function toEvenHex(n) {
37
- let h = n.toString(16);
38
- if (h.length % 2 !== 0)
39
- h = `0${h}`;
40
- return `0x${h}`;
41
- }
42
- /**
43
- * POST JSON with a hard timeout via AbortController.
44
- * Node's global fetch has no default timeout.
45
- */
46
- async function postJson(url, body, timeoutMs) {
47
- const ac = new AbortController();
48
- const timer = setTimeout(() => ac.abort(), timeoutMs);
49
- try {
50
- const res = await fetch(url, {
51
- method: 'POST',
52
- headers: { 'Content-Type': 'application/json' },
53
- body: JSON.stringify(body),
54
- signal: ac.signal,
55
- });
56
- if (!res.ok) {
57
- const err = await res.text();
58
- throw new Error(`POST ${url} failed (${res.status}): ${err}`);
59
- }
60
- return (await res.json());
61
- }
62
- catch (e) {
63
- if (e.name === 'AbortError') {
64
- throw new Error(`POST ${url} timed out after ${timeoutMs}ms`);
65
- }
66
- throw e;
67
- }
68
- finally {
69
- clearTimeout(timer);
70
- }
71
- }
72
- export class InsufficientBalanceError extends Error {
73
- balance;
74
- required;
75
- tokenAddress;
76
- constructor(balance, required, tokenAddress) {
77
- super(`Insufficient token balance: have ${balance}, need ${required} (token ${tokenAddress})`);
78
- this.balance = balance;
79
- this.required = required;
80
- this.tokenAddress = tokenAddress;
81
- this.name = 'InsufficientBalanceError';
82
- }
83
- }
84
- // ─── Helpers ──────────────────────────────────────────────────────────────────
85
- /**
86
- * Convert the backend's hex-string UserOp to viem's bigint-typed UserOperation<'0.8'>.
87
- */
88
- function parseUserOp(raw) {
89
- return {
90
- sender: raw.sender,
91
- nonce: BigInt(raw.nonce),
92
- callData: raw.callData,
93
- callGasLimit: BigInt(raw.callGasLimit),
94
- verificationGasLimit: BigInt(raw.verificationGasLimit),
95
- preVerificationGas: BigInt(raw.preVerificationGas),
96
- maxFeePerGas: BigInt(raw.maxFeePerGas),
97
- maxPriorityFeePerGas: BigInt(raw.maxPriorityFeePerGas),
98
- ...(raw.paymaster && { paymaster: raw.paymaster }),
99
- ...(raw.paymasterVerificationGasLimit && {
100
- paymasterVerificationGasLimit: BigInt(raw.paymasterVerificationGasLimit),
101
- }),
102
- ...(raw.paymasterPostOpGasLimit && {
103
- paymasterPostOpGasLimit: BigInt(raw.paymasterPostOpGasLimit),
104
- }),
105
- ...(raw.paymasterData && { paymasterData: raw.paymasterData }),
106
- ...(raw.factory && { factory: raw.factory }),
107
- ...(raw.factoryData && { factoryData: raw.factoryData }),
108
- signature: '0x',
109
- };
110
- }
111
- /**
112
- * Convert UserOperation<'0.8'> bigint fields → hex strings for JSON serialization.
113
- * The Go backend expects all numeric fields as 0x-prefixed hex strings.
114
- */
115
- function serializeUserOp(op) {
116
- const toHex = (n) => `0x${n.toString(16)}`;
117
- return {
118
- sender: op.sender,
119
- nonce: toHex(op.nonce),
120
- callData: op.callData,
121
- callGasLimit: toHex(op.callGasLimit),
122
- verificationGasLimit: toHex(op.verificationGasLimit),
123
- preVerificationGas: toHex(op.preVerificationGas),
124
- maxFeePerGas: toHex(op.maxFeePerGas),
125
- maxPriorityFeePerGas: toHex(op.maxPriorityFeePerGas),
126
- ...(op.paymaster && { paymaster: op.paymaster }),
127
- ...(op.paymasterVerificationGasLimit !== undefined && {
128
- paymasterVerificationGasLimit: toHex(op.paymasterVerificationGasLimit),
129
- }),
130
- ...(op.paymasterPostOpGasLimit !== undefined && {
131
- paymasterPostOpGasLimit: toHex(op.paymasterPostOpGasLimit),
132
- }),
133
- ...(op.paymasterData && { paymasterData: op.paymasterData }),
134
- ...(op.factory && { factory: op.factory }),
135
- ...(op.factoryData && { factoryData: op.factoryData }),
136
- ...(op.signature && { signature: op.signature }),
137
- };
138
- }
139
- // ─── Main function ─────────────────────────────────────────────────────────────
140
- export async function smartDeposit(params) {
141
- const { privateKey, rpcUrl, allsetApiUrl, tokenAddress, amount, bridgeAddress, depositCalldata, requestTimeoutMs = 60_000, } = params;
142
- const eoa = privateKeyToAccount(privateKey);
143
- // No chain object needed — chainId is fetched dynamically from the RPC
144
- const publicClient = createPublicClient({ transport: http(rpcUrl) });
145
- // Step 1: One-shot balance check — caller is responsible for funding the EOA first
146
- const tokenBalance = (await publicClient.readContract({
147
- address: tokenAddress,
148
- abi: ERC20_BALANCEOF_ABI,
149
- functionName: 'balanceOf',
150
- args: [eoa.address],
151
- }));
152
- if (tokenBalance < amount) {
153
- throw new InsufficientBalanceError(tokenBalance, amount, tokenAddress);
154
- }
155
- // Fetch chainId once — used for EIP-7702 auth and UserOp signing
156
- const chainId = await publicClient.getChainId();
157
- // Step 2: Build request auth signature (proves caller owns the private key).
158
- // Preimage: abi.encode(domainTag, chainId, nonce, from, tokenAddress, amount, bridgeAddress, depositCalldata, timestamp)
159
- // - Domain tag prevents cross-protocol signature collisions.
160
- // - chainId prevents cross-chain replay.
161
- // - nonce (random 32 bytes) prevents in-protocol replay; backend must track used nonces.
162
- // - abi.encode (not encodePacked) eliminates dynamic-field collision ambiguity.
163
- const timestamp = Math.floor(Date.now() / 1000);
164
- const nonceBytes = crypto.getRandomValues(new Uint8Array(32));
165
- const nonce = `0x${Array.from(nonceBytes, (b) => b.toString(16).padStart(2, '0')).join('')}`;
166
- const DOMAIN_TAG = 'AllSet Portal authSig v1';
167
- const msgHash = keccak256(encodeAbiParameters([
168
- { type: 'string' },
169
- { type: 'uint256' },
170
- { type: 'bytes32' },
171
- { type: 'address' },
172
- { type: 'address' },
173
- { type: 'uint256' },
174
- { type: 'address' },
175
- { type: 'bytes' },
176
- { type: 'uint256' },
177
- ], [
178
- DOMAIN_TAG,
179
- BigInt(chainId),
180
- nonce,
181
- eoa.address,
182
- tokenAddress,
183
- amount,
184
- bridgeAddress,
185
- depositCalldata,
186
- BigInt(timestamp),
187
- ]));
188
- const authSig = await eoa.signMessage({ message: { raw: msgHash } });
189
- // Step 3: POST /userop/prepare (3 attempts with exponential backoff: 0, 500, 1500ms)
190
- const prepareReq = {
191
- rpcUrl,
192
- from: eoa.address,
193
- tokenAddress,
194
- amount: amount.toString(),
195
- bridgeAddress,
196
- depositCalldata,
197
- chainId,
198
- nonce,
199
- timestamp,
200
- authSig,
201
- };
202
- const PREPARE_DELAYS = [0, 500, 1500];
203
- let prepared;
204
- for (let attempt = 0; attempt < PREPARE_DELAYS.length; attempt++) {
205
- if (PREPARE_DELAYS[attempt] > 0) {
206
- await new Promise((r) => setTimeout(r, PREPARE_DELAYS[attempt]));
207
- }
208
- try {
209
- prepared = await postJson(`${allsetApiUrl}/userop/prepare`, prepareReq, requestTimeoutMs);
210
- break;
211
- }
212
- catch (e) {
213
- const isLast = attempt === PREPARE_DELAYS.length - 1;
214
- // Retry on network errors and 5xx/429 (message contains status code)
215
- const msg = e.message ?? '';
216
- const isRetryable = !msg.match(/POST .+ failed \([1-4][0-9]{2}\)/) || msg.includes('(429)') || msg.includes('(5');
217
- if (isLast || !isRetryable)
218
- throw e;
219
- }
220
- }
221
- // Step 4: Pin delegate address against trusted allowlist
222
- if (!TRUSTED_DELEGATES.has(prepared.delegate7702Address.toLowerCase())) {
223
- throw new Error(`smartDeposit: untrusted delegate address returned by backend: ${prepared.delegate7702Address}`);
224
- }
225
- // Step 5: Sign EIP-7702 authorization.
226
- // We always re-sign to ensure the EOA is delegated to the correct v0.8 impl,
227
- // even if a prior (possibly outdated) delegation exists.
228
- let eip7702Auth;
229
- if (prepared.needsAuthorization) {
230
- // Use 'pending' so mempool txs from this EOA are counted in the nonce.
231
- const accountNonce = await publicClient.getTransactionCount({
232
- address: eoa.address,
233
- blockTag: 'pending',
234
- });
235
- const signed = await eoa.signAuthorization({
236
- address: prepared.delegate7702Address,
237
- chainId,
238
- nonce: accountNonce,
239
- });
240
- const yParity = signed.yParity ?? 0;
241
- eip7702Auth = {
242
- address: prepared.delegate7702Address,
243
- chainId: toEvenHex(chainId),
244
- nonce: toEvenHex(accountNonce),
245
- yParity: toEvenHex(yParity),
246
- r: `0x${BigInt(signed.r).toString(16).padStart(64, '0')}`,
247
- s: `0x${BigInt(signed.s).toString(16).padStart(64, '0')}`,
248
- };
249
- }
250
- // Step 6: Parse backend response + sign UserOperation (v0.8 uses EIP-712 typed data)
251
- const userOpToSign = parseUserOp(prepared.unsignedUserOp);
252
- // v0.8 requires EIP-712 signTypedData, NOT signMessage/personal_sign
253
- const typedData = getUserOperationTypedData({
254
- chainId,
255
- entryPointAddress: ENTRY_POINT_V08,
256
- userOperation: { ...userOpToSign, signature: '0x' },
257
- });
258
- const signature = await eoa.signTypedData(typedData);
259
- const signedUserOp = { ...userOpToSign, signature };
260
- // Step 7: POST /userop/submit (single attempt — UserOps are not idempotent)
261
- const serialized = serializeUserOp(signedUserOp);
262
- if (eip7702Auth) {
263
- serialized.eip7702Auth = eip7702Auth;
264
- }
265
- const submitReq = {
266
- rpcUrl,
267
- signedUserOp: serialized,
268
- };
269
- const { txHash, userOpHash: returnedUserOpHash } = await postJson(`${allsetApiUrl}/userop/submit`, submitReq, requestTimeoutMs);
270
- return {
271
- txHash,
272
- userOpHash: returnedUserOpHash,
273
- userAddress: eoa.address,
274
- };
275
- }
@@ -1,130 +0,0 @@
1
- /**
2
- * evm-executor.ts — EVM client utilities using viem
3
- *
4
- * Provides createEvmExecutor() to create viem wallet and public clients,
5
- * and createEvmWallet() to generate or load EVM wallets.
6
- *
7
- * Wallet keyfiles are managed by the user at ~/.evm/keys/ or custom paths.
8
- * Expected format: { "privateKey": "...", "address": "..." (optional) }
9
- */
10
- import { type Account, type Chain, type PublicClient, type WalletClient } from 'viem';
11
- /**
12
- * Account-compatible wallet returned by createEvmWallet().
13
- *
14
- * Includes the normalized private key so generated accounts can be persisted
15
- * or reconstructed by the caller.
16
- */
17
- export type EvmAccount = Account & {
18
- privateKey: `0x${string}`;
19
- };
20
- /**
21
- * Get the default EVM keys directory (~/.evm/keys).
22
- */
23
- export declare function getEvmKeysDir(): string;
24
- /**
25
- * Create or load an EVM wallet and return an Account-compatible object.
26
- *
27
- * @param keyOrPath - Optional. Can be:
28
- * - Omitted: generates a new random wallet
29
- * - Private key (64 hex chars, with or without 0x): derives account from it
30
- * - File path (contains `/` or `~`, or ends with `.json`): loads from JSON keyfile
31
- *
32
- * The keyfile must be a JSON file containing:
33
- * - `privateKey` (required): hex string, with or without 0x prefix
34
- * - `address` (optional): for user reference only
35
- *
36
- * It is the user's responsibility to create and manage keyfiles.
37
- * Generated accounts expose `privateKey` so callers can persist them.
38
- *
39
- * @returns Account-compatible object with viem signing methods and `privateKey`
40
- *
41
- * @example
42
- * ```ts
43
- * // Generate new wallet
44
- * const account = createEvmWallet();
45
- * console.log(account.address); // 0x...
46
- * console.log(account.privateKey); // persist this if you generated the wallet
47
- *
48
- * // Derive from private key
49
- * const account = createEvmWallet('0x1234...64hexchars');
50
- *
51
- * // Load from keyfile
52
- * const account = createEvmWallet('~/.evm/keys/default.json');
53
- *
54
- * // Use with createEvmExecutor
55
- * const { walletClient, publicClient } = createEvmExecutor(account, rpcUrl, chainId);
56
- * ```
57
- *
58
- * @example Keyfile format
59
- * ```json
60
- * {
61
- * "privateKey": "abc123...64hexchars",
62
- * "address": "0x..." // optional, for reference
63
- * }
64
- * ```
65
- */
66
- export declare function createEvmWallet(keyOrPath?: string): EvmAccount;
67
- /** ERC20 ABI for allowance and approve */
68
- export declare const ERC20_ABI: readonly [{
69
- readonly name: "approve";
70
- readonly type: "function";
71
- readonly stateMutability: "nonpayable";
72
- readonly inputs: readonly [{
73
- readonly type: "address";
74
- readonly name: "spender";
75
- }, {
76
- readonly type: "uint256";
77
- readonly name: "amount";
78
- }];
79
- readonly outputs: readonly [{
80
- readonly type: "bool";
81
- }];
82
- }, {
83
- readonly name: "allowance";
84
- readonly type: "function";
85
- readonly stateMutability: "view";
86
- readonly inputs: readonly [{
87
- readonly type: "address";
88
- readonly name: "owner";
89
- }, {
90
- readonly type: "address";
91
- readonly name: "spender";
92
- }];
93
- readonly outputs: readonly [{
94
- readonly type: "uint256";
95
- }];
96
- }];
97
- /** Bundled supported chain mappings */
98
- export declare const CHAIN_MAP: Record<number, Chain>;
99
- /**
100
- * EVM clients returned by createEvmExecutor.
101
- */
102
- export interface EvmClients {
103
- walletClient: WalletClient;
104
- publicClient: PublicClient;
105
- }
106
- /**
107
- * Create viem wallet and public clients for EVM operations.
108
- *
109
- * @param account - viem Account from createEvmWallet() or privateKeyToAccount()
110
- * @param rpcUrl - RPC endpoint URL
111
- * @param chainId - Chain ID (11155111 for Sepolia, 421614 for Arbitrum Sepolia, 8453 for Base)
112
- * @returns Object with walletClient and publicClient
113
- *
114
- * @example
115
- * ```ts
116
- * // Using Account from createEvmWallet (loads from keyfile)
117
- * const account = createEvmWallet('~/.evm/keys/default.json');
118
- * const { walletClient, publicClient } = createEvmExecutor(account, 'https://sepolia-rollup.arbitrum.io/rpc', 421614);
119
- *
120
- * // Using viem's privateKeyToAccount directly
121
- * import { privateKeyToAccount } from 'viem/accounts';
122
- * const account = privateKeyToAccount('0xabc123...');
123
- * const { walletClient, publicClient } = createEvmExecutor(account, rpcUrl, chainId);
124
- *
125
- * // Use clients for bridge deposit
126
- * await allset.sendToFast({ ..., evmClients: { walletClient, publicClient } });
127
- * ```
128
- */
129
- export declare function createEvmExecutor(account: Account, rpcUrl: string, chainId: number): EvmClients;
130
- //# sourceMappingURL=evm-executor.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"evm-executor.d.ts","sourceRoot":"","sources":["../../src/node/evm-executor.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAIH,OAAO,EAKL,KAAK,OAAO,EACZ,KAAK,KAAK,EACV,KAAK,YAAY,EACjB,KAAK,YAAY,EAClB,MAAM,MAAM,CAAC;AAId;;;;;GAKG;AACH,MAAM,MAAM,UAAU,GAAG,OAAO,GAAG;IACjC,UAAU,EAAE,KAAK,MAAM,EAAE,CAAC;CAC3B,CAAC;AASF;;GAEG;AACH,wBAAgB,aAAa,IAAI,MAAM,CAEtC;AAwBD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyCG;AACH,wBAAgB,eAAe,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,UAAU,CAwB9D;AAED,0CAA0C;AAC1C,eAAO,MAAM,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAGpB,CAAC;AAEH,uCAAuC;AACvC,eAAO,MAAM,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,KAAK,CAM3C,CAAC;AAEF;;GAEG;AACH,MAAM,WAAW,UAAU;IACzB,YAAY,EAAE,YAAY,CAAC;IAC3B,YAAY,EAAE,YAAY,CAAC;CAC5B;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,iBAAiB,CAC/B,OAAO,EAAE,OAAO,EAChB,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,MAAM,GACd,UAAU,CAoBZ"}