@fastxyz/allset-sdk 0.1.12 → 1.0.1

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 +322 -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,160 +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 { existsSync, readFileSync } from 'node:fs';
11
- import { join } from 'node:path';
12
- import { createPublicClient, createWalletClient, http, parseAbi, } from 'viem';
13
- import { generatePrivateKey, privateKeyToAccount } from 'viem/accounts';
14
- import { arbitrum, arbitrumSepolia, base, mainnet as ethereum, sepolia } from 'viem/chains';
15
- // Default EVM keys directory
16
- const DEFAULT_EVM_KEYS_DIR = join(process.env.HOME || process.env.USERPROFILE || '', '.evm', 'keys');
17
- /**
18
- * Get the default EVM keys directory (~/.evm/keys).
19
- */
20
- export function getEvmKeysDir() {
21
- return DEFAULT_EVM_KEYS_DIR;
22
- }
23
- /**
24
- * Expand ~ to home directory
25
- */
26
- function expandPath(path) {
27
- if (path.startsWith('~/')) {
28
- const home = process.env.HOME || process.env.USERPROFILE || '';
29
- return path.replace('~', home);
30
- }
31
- return path;
32
- }
33
- /**
34
- * Detect if a string is a file path (vs a private key)
35
- */
36
- function isFilePath(input) {
37
- return input.includes('/') || input.startsWith('~') || input.endsWith('.json');
38
- }
39
- function normalizePrivateKey(privateKey) {
40
- return (privateKey.startsWith('0x') ? privateKey : `0x${privateKey}`);
41
- }
42
- /**
43
- * Create or load an EVM wallet and return an Account-compatible object.
44
- *
45
- * @param keyOrPath - Optional. Can be:
46
- * - Omitted: generates a new random wallet
47
- * - Private key (64 hex chars, with or without 0x): derives account from it
48
- * - File path (contains `/` or `~`, or ends with `.json`): loads from JSON keyfile
49
- *
50
- * The keyfile must be a JSON file containing:
51
- * - `privateKey` (required): hex string, with or without 0x prefix
52
- * - `address` (optional): for user reference only
53
- *
54
- * It is the user's responsibility to create and manage keyfiles.
55
- * Generated accounts expose `privateKey` so callers can persist them.
56
- *
57
- * @returns Account-compatible object with viem signing methods and `privateKey`
58
- *
59
- * @example
60
- * ```ts
61
- * // Generate new wallet
62
- * const account = createEvmWallet();
63
- * console.log(account.address); // 0x...
64
- * console.log(account.privateKey); // persist this if you generated the wallet
65
- *
66
- * // Derive from private key
67
- * const account = createEvmWallet('0x1234...64hexchars');
68
- *
69
- * // Load from keyfile
70
- * const account = createEvmWallet('~/.evm/keys/default.json');
71
- *
72
- * // Use with createEvmExecutor
73
- * const { walletClient, publicClient } = createEvmExecutor(account, rpcUrl, chainId);
74
- * ```
75
- *
76
- * @example Keyfile format
77
- * ```json
78
- * {
79
- * "privateKey": "abc123...64hexchars",
80
- * "address": "0x..." // optional, for reference
81
- * }
82
- * ```
83
- */
84
- export function createEvmWallet(keyOrPath) {
85
- let key;
86
- if (!keyOrPath) {
87
- // Generate new wallet
88
- key = generatePrivateKey();
89
- }
90
- else if (isFilePath(keyOrPath)) {
91
- // Load from file
92
- const fullPath = expandPath(keyOrPath);
93
- if (!existsSync(fullPath)) {
94
- throw new Error(`Wallet file not found: ${keyOrPath}`);
95
- }
96
- const content = readFileSync(fullPath, 'utf-8');
97
- const data = JSON.parse(content);
98
- if (!data.privateKey) {
99
- throw new Error(`Invalid wallet file: missing privateKey`);
100
- }
101
- key = normalizePrivateKey(data.privateKey);
102
- }
103
- else {
104
- // Treat as private key
105
- key = normalizePrivateKey(keyOrPath);
106
- }
107
- return Object.assign(privateKeyToAccount(key), { privateKey: key });
108
- }
109
- /** ERC20 ABI for allowance and approve */
110
- export const ERC20_ABI = parseAbi([
111
- 'function approve(address spender, uint256 amount) returns (bool)',
112
- 'function allowance(address owner, address spender) view returns (uint256)',
113
- ]);
114
- /** Bundled supported chain mappings */
115
- export const CHAIN_MAP = {
116
- 1: ethereum,
117
- 11155111: sepolia,
118
- 421614: arbitrumSepolia,
119
- 42161: arbitrum,
120
- 8453: base,
121
- };
122
- /**
123
- * Create viem wallet and public clients for EVM operations.
124
- *
125
- * @param account - viem Account from createEvmWallet() or privateKeyToAccount()
126
- * @param rpcUrl - RPC endpoint URL
127
- * @param chainId - Chain ID (11155111 for Sepolia, 421614 for Arbitrum Sepolia, 8453 for Base)
128
- * @returns Object with walletClient and publicClient
129
- *
130
- * @example
131
- * ```ts
132
- * // Using Account from createEvmWallet (loads from keyfile)
133
- * const account = createEvmWallet('~/.evm/keys/default.json');
134
- * const { walletClient, publicClient } = createEvmExecutor(account, 'https://sepolia-rollup.arbitrum.io/rpc', 421614);
135
- *
136
- * // Using viem's privateKeyToAccount directly
137
- * import { privateKeyToAccount } from 'viem/accounts';
138
- * const account = privateKeyToAccount('0xabc123...');
139
- * const { walletClient, publicClient } = createEvmExecutor(account, rpcUrl, chainId);
140
- *
141
- * // Use clients for bridge deposit
142
- * await allset.sendToFast({ ..., evmClients: { walletClient, publicClient } });
143
- * ```
144
- */
145
- export function createEvmExecutor(account, rpcUrl, chainId) {
146
- const chain = CHAIN_MAP[chainId];
147
- if (!chain) {
148
- throw new Error(`Unsupported EVM chain ID: ${chainId}. Supported: ${Object.keys(CHAIN_MAP).join(', ')}`);
149
- }
150
- const walletClient = createWalletClient({
151
- account,
152
- chain,
153
- transport: http(rpcUrl),
154
- });
155
- const publicClient = createPublicClient({
156
- chain,
157
- transport: http(rpcUrl),
158
- });
159
- return { walletClient, publicClient };
160
- }
@@ -1,15 +0,0 @@
1
- export * from '../core/index.js';
2
- export * from './eip7702.js';
3
- export { AllSetProvider, getAllSetDir, getEvmKeysDir as getAllSetEvmKeysDir, ensureAllSetDirs, initUserConfig, } from './provider.js';
4
- export { createEvmExecutor, createEvmWallet, getEvmKeysDir, } from './evm-executor.js';
5
- export { loadNetworksConfig, getNetworkConfig, getChainConfig, getTokenConfig, clearConfigCache, } from './config.js';
6
- export type { BridgeProvider, BridgeParams, BridgeResult, FastWalletLike, AllSetChainConfig, AllSetTokenInfo, SendToFastParams, SendToExternalParams, ExecuteIntentParams, } from './types.js';
7
- export type { Intent } from '../intents.js';
8
- export type { EvmSignResult } from './bridge.js';
9
- export type { EvmAccount, EvmClients } from './evm-executor.js';
10
- export type { NetworkConfig, ChainConfig, TokenConfig, AllNetworksConfig } from './config.js';
11
- export type { AllSetProviderOptions } from './provider.js';
12
- export declare function evmSign(...args: Parameters<typeof import('./bridge.js').evmSign>): ReturnType<typeof import('./bridge.js').evmSign>;
13
- export declare function executeBridge(...args: Parameters<typeof import('./bridge.js').executeBridge>): ReturnType<typeof import('./bridge.js').executeBridge>;
14
- export declare function executeIntent(...args: Parameters<typeof import('./bridge.js').executeIntent>): ReturnType<typeof import('./bridge.js').executeIntent>;
15
- //# sourceMappingURL=index.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/node/index.ts"],"names":[],"mappings":"AAAA,cAAc,kBAAkB,CAAC;AACjC,cAAc,cAAc,CAAC;AAE7B,OAAO,EACL,cAAc,EACd,YAAY,EACZ,aAAa,IAAI,mBAAmB,EACpC,gBAAgB,EAChB,cAAc,GACf,MAAM,eAAe,CAAC;AAEvB,OAAO,EACL,iBAAiB,EACjB,eAAe,EACf,aAAa,GACd,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,kBAAkB,EAClB,gBAAgB,EAChB,cAAc,EACd,cAAc,EACd,gBAAgB,GACjB,MAAM,aAAa,CAAC;AAErB,YAAY,EACV,cAAc,EACd,YAAY,EACZ,YAAY,EACZ,cAAc,EACd,iBAAiB,EACjB,eAAe,EACf,gBAAgB,EAChB,oBAAoB,EACpB,mBAAmB,GACpB,MAAM,YAAY,CAAC;AAEpB,YAAY,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AAC5C,YAAY,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AACjD,YAAY,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAChE,YAAY,EAAE,aAAa,EAAE,WAAW,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAC9F,YAAY,EAAE,qBAAqB,EAAE,MAAM,eAAe,CAAC;AAE3D,wBAAsB,OAAO,CAC3B,GAAG,IAAI,EAAE,UAAU,CAAC,cAAc,aAAa,EAAE,OAAO,CAAC,GACxD,UAAU,CAAC,cAAc,aAAa,EAAE,OAAO,CAAC,CAGlD;AAED,wBAAsB,aAAa,CACjC,GAAG,IAAI,EAAE,UAAU,CAAC,cAAc,aAAa,EAAE,aAAa,CAAC,GAC9D,UAAU,CAAC,cAAc,aAAa,EAAE,aAAa,CAAC,CAGxD;AAED,wBAAsB,aAAa,CACjC,GAAG,IAAI,EAAE,UAAU,CAAC,cAAc,aAAa,EAAE,aAAa,CAAC,GAC9D,UAAU,CAAC,cAAc,aAAa,EAAE,aAAa,CAAC,CAGxD"}
@@ -1,17 +0,0 @@
1
- export * from '../core/index.js';
2
- export * from './eip7702.js';
3
- export { AllSetProvider, getAllSetDir, getEvmKeysDir as getAllSetEvmKeysDir, ensureAllSetDirs, initUserConfig, } from './provider.js';
4
- export { createEvmExecutor, createEvmWallet, getEvmKeysDir, } from './evm-executor.js';
5
- export { loadNetworksConfig, getNetworkConfig, getChainConfig, getTokenConfig, clearConfigCache, } from './config.js';
6
- export async function evmSign(...args) {
7
- const mod = await import('./bridge.js');
8
- return mod.evmSign(...args);
9
- }
10
- export async function executeBridge(...args) {
11
- const mod = await import('./bridge.js');
12
- return mod.executeBridge(...args);
13
- }
14
- export async function executeIntent(...args) {
15
- const mod = await import('./bridge.js');
16
- return mod.executeIntent(...args);
17
- }
@@ -1,162 +0,0 @@
1
- /**
2
- * provider.ts — AllSetProvider for bridge configuration and operations
3
- *
4
- * Similar to FastProvider, AllSetProvider manages network configuration
5
- * and provides the bridge() method for bridging tokens.
6
- */
7
- import type { NetworkConfig, ChainConfig, TokenConfig, AllNetworksConfig } from './config.js';
8
- import type { BridgeResult, SendToFastParams, SendToExternalParams, ExecuteIntentParams } from './types.js';
9
- export interface AllSetProviderOptions {
10
- /**
11
- * Network to use: 'testnet' or 'mainnet'
12
- * @default 'testnet'
13
- */
14
- network?: 'testnet' | 'mainnet';
15
- /**
16
- * Custom path to networks.json config file.
17
- * If not provided, loads from:
18
- * 1. ~/.allset/networks.json (user override)
19
- * 2. Embedded package defaults
20
- */
21
- configPath?: string;
22
- /**
23
- * Custom cross-sign URL (overrides config)
24
- */
25
- crossSignUrl?: string;
26
- }
27
- /**
28
- * AllSetProvider manages AllSet bridge configuration.
29
- *
30
- * @example
31
- * ```ts
32
- * // Default testnet configuration
33
- * const provider = new AllSetProvider();
34
- *
35
- * // Mainnet configuration
36
- * const provider = new AllSetProvider({ network: 'mainnet' });
37
- *
38
- * // Custom config file
39
- * const provider = new AllSetProvider({ configPath: './my-config.json' });
40
- *
41
- * // Access configuration
42
- * const chainConfig = provider.getChainConfig('arbitrum-sepolia');
43
- * const tokenConfig = provider.getTokenConfig('arbitrum-sepolia', 'USDC');
44
- * ```
45
- */
46
- export declare class AllSetProvider {
47
- private readonly _network;
48
- private readonly _config;
49
- private readonly _networkConfig;
50
- private readonly _crossSignUrl;
51
- constructor(options?: AllSetProviderOptions);
52
- /**
53
- * Get the current network name.
54
- */
55
- get network(): 'testnet' | 'mainnet';
56
- /**
57
- * Get the cross-sign service URL.
58
- */
59
- get crossSignUrl(): string;
60
- /**
61
- * Get list of supported chain names.
62
- */
63
- get chains(): string[];
64
- /**
65
- * Get configuration for a specific chain.
66
- */
67
- getChainConfig(chain: string): ChainConfig | null;
68
- /**
69
- * Get token configuration for a chain.
70
- * Handles testUSDC -> USDC normalization for testnet.
71
- */
72
- getTokenConfig(chain: string, token: string): TokenConfig | null;
73
- /**
74
- * Get the full network configuration.
75
- */
76
- getNetworkConfig(): NetworkConfig;
77
- /**
78
- * Get the raw config (both testnet and mainnet).
79
- */
80
- getRawConfig(): AllNetworksConfig;
81
- /**
82
- * Deposit tokens from EVM chain to Fast network.
83
- *
84
- * @example
85
- * ```ts
86
- * const result = await allset.sendToFast({
87
- * chain: 'arbitrum-sepolia',
88
- * token: 'USDC',
89
- * amount: '1000000',
90
- * from: '0xYourEvmAddress',
91
- * to: 'fast1receiveraddress',
92
- * evmClients,
93
- * });
94
- * ```
95
- */
96
- sendToFast(params: SendToFastParams): Promise<BridgeResult>;
97
- /**
98
- * Withdraw tokens from Fast network to EVM chain.
99
- *
100
- * @example
101
- * ```ts
102
- * const result = await allset.sendToExternal({
103
- * chain: 'base',
104
- * token: 'USDC',
105
- * amount: '1000000',
106
- * from: fastWallet.address,
107
- * to: '0xReceiverEvmAddress',
108
- * fastWallet,
109
- * });
110
- * ```
111
- */
112
- sendToExternal(params: SendToExternalParams): Promise<BridgeResult>;
113
- /**
114
- * Execute custom intents on an EVM chain.
115
- *
116
- * This is the advanced API for composing custom operations like swaps,
117
- * multi-step transactions, or protocol integrations.
118
- *
119
- * @example
120
- * ```ts
121
- * import { buildTransferIntent, buildExecuteIntent } from '@fastxyz/allset-sdk';
122
- *
123
- * // Simple transfer
124
- * const result = await allset.executeIntent({
125
- * chain: 'base',
126
- * fastWallet, // Compatible Fast wallet, e.g. FastWallet from @fastxyz/sdk
127
- * token: 'USDC',
128
- * amount: '1000000',
129
- * intents: [buildTransferIntent(USDC_ADDRESS, '0xRecipient')],
130
- * });
131
- *
132
- * // Custom contract call
133
- * const result = await allset.executeIntent({
134
- * chain: 'base',
135
- * fastWallet, // Compatible Fast wallet, e.g. FastWallet from @fastxyz/sdk
136
- * token: 'USDC',
137
- * amount: '1000000',
138
- * intents: [buildExecuteIntent(CONTRACT, calldata)],
139
- * externalAddress: CONTRACT,
140
- * });
141
- * ```
142
- */
143
- executeIntent(params: ExecuteIntentParams): Promise<BridgeResult>;
144
- }
145
- /**
146
- * Get the AllSet home directory (~/.allset).
147
- */
148
- export declare function getAllSetDir(): string;
149
- /**
150
- * Get the EVM keys directory (~/.allset/.evm/keys).
151
- */
152
- export declare function getEvmKeysDir(): string;
153
- /**
154
- * Ensure the AllSet directory structure exists.
155
- */
156
- export declare function ensureAllSetDirs(): void;
157
- /**
158
- * Initialize user config by writing the embedded defaults to ~/.allset/.
159
- * Does nothing if user config already exists.
160
- */
161
- export declare function initUserConfig(): string;
162
- //# sourceMappingURL=provider.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../../src/node/provider.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAKH,OAAO,KAAK,EAAE,aAAa,EAAE,WAAW,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAC9F,OAAO,KAAK,EAAE,YAAY,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAa5G,MAAM,WAAW,qBAAqB;IACpC;;;OAGG;IACH,OAAO,CAAC,EAAE,SAAS,GAAG,SAAS,CAAC;IAEhC;;;;;OAKG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IAEpB;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AA4CD;;;;;;;;;;;;;;;;;;GAkBG;AACH,qBAAa,cAAc;IACzB,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAwB;IACjD,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAoB;IAC5C,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAgB;IAC/C,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAS;gBAE3B,OAAO,GAAE,qBAA0B;IAY/C;;OAEG;IACH,IAAI,OAAO,IAAI,SAAS,GAAG,SAAS,CAEnC;IAED;;OAEG;IACH,IAAI,YAAY,IAAI,MAAM,CAEzB;IAED;;OAEG;IACH,IAAI,MAAM,IAAI,MAAM,EAAE,CAErB;IAED;;OAEG;IACH,cAAc,CAAC,KAAK,EAAE,MAAM,GAAG,WAAW,GAAG,IAAI;IAIjD;;;OAGG;IACH,cAAc,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,WAAW,GAAG,IAAI;IAehE;;OAEG;IACH,gBAAgB,IAAI,aAAa;IAIjC;;OAEG;IACH,YAAY,IAAI,iBAAiB;IAIjC;;;;;;;;;;;;;;OAcG;IACG,UAAU,CAAC,MAAM,EAAE,gBAAgB,GAAG,OAAO,CAAC,YAAY,CAAC;IAoBjE;;;;;;;;;;;;;;OAcG;IACG,cAAc,CAAC,MAAM,EAAE,oBAAoB,GAAG,OAAO,CAAC,YAAY,CAAC;IAgBzE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA6BG;IACG,aAAa,CAAC,MAAM,EAAE,mBAAmB,GAAG,OAAO,CAAC,YAAY,CAAC;CAKxE;AAMD;;GAEG;AACH,wBAAgB,YAAY,IAAI,MAAM,CAErC;AAED;;GAEG;AACH,wBAAgB,aAAa,IAAI,MAAM,CAEtC;AAED;;GAEG;AACH,wBAAgB,gBAAgB,IAAI,IAAI,CAOvC;AAED;;;GAGG;AACH,wBAAgB,cAAc,IAAI,MAAM,CAevC"}
@@ -1,272 +0,0 @@
1
- /**
2
- * provider.ts — AllSetProvider for bridge configuration and operations
3
- *
4
- * Similar to FastProvider, AllSetProvider manages network configuration
5
- * and provides the bridge() method for bridging tokens.
6
- */
7
- import { existsSync, readFileSync, mkdirSync, writeFileSync } from 'node:fs';
8
- import { join } from 'node:path';
9
- import { DEFAULT_NETWORKS_CONFIG } from '../default-config.js';
10
- // ---------------------------------------------------------------------------
11
- // Constants
12
- // ---------------------------------------------------------------------------
13
- const ALLSET_DIR = join(process.env.HOME || process.env.USERPROFILE || '', '.allset');
14
- const EVM_KEYS_DIR = join(ALLSET_DIR, '.evm', 'keys');
15
- // ---------------------------------------------------------------------------
16
- // Helper Functions
17
- // ---------------------------------------------------------------------------
18
- function expandHome(path) {
19
- if (path.startsWith('~/')) {
20
- const home = process.env.HOME || process.env.USERPROFILE || '';
21
- return path.replace('~', home);
22
- }
23
- return path;
24
- }
25
- function getUserConfigPath() {
26
- return join(ALLSET_DIR, 'networks.json');
27
- }
28
- function loadConfig(customPath) {
29
- // Priority: customPath > ~/.allset/networks.json > embedded default config
30
- const paths = [
31
- customPath,
32
- getUserConfigPath(),
33
- ].filter((p) => !!p);
34
- for (const configPath of paths) {
35
- const resolved = expandHome(configPath);
36
- if (existsSync(resolved)) {
37
- try {
38
- const raw = readFileSync(resolved, 'utf-8');
39
- return JSON.parse(raw);
40
- }
41
- catch {
42
- // Continue to next path
43
- }
44
- }
45
- }
46
- return structuredClone(DEFAULT_NETWORKS_CONFIG);
47
- }
48
- // ---------------------------------------------------------------------------
49
- // AllSetProvider Class
50
- // ---------------------------------------------------------------------------
51
- /**
52
- * AllSetProvider manages AllSet bridge configuration.
53
- *
54
- * @example
55
- * ```ts
56
- * // Default testnet configuration
57
- * const provider = new AllSetProvider();
58
- *
59
- * // Mainnet configuration
60
- * const provider = new AllSetProvider({ network: 'mainnet' });
61
- *
62
- * // Custom config file
63
- * const provider = new AllSetProvider({ configPath: './my-config.json' });
64
- *
65
- * // Access configuration
66
- * const chainConfig = provider.getChainConfig('arbitrum-sepolia');
67
- * const tokenConfig = provider.getTokenConfig('arbitrum-sepolia', 'USDC');
68
- * ```
69
- */
70
- export class AllSetProvider {
71
- _network;
72
- _config;
73
- _networkConfig;
74
- _crossSignUrl;
75
- constructor(options = {}) {
76
- this._network = options.network ?? 'testnet';
77
- this._config = loadConfig(options.configPath);
78
- this._networkConfig = this._config[this._network];
79
- if (!this._networkConfig) {
80
- throw new Error(`Network "${this._network}" not found in config`);
81
- }
82
- this._crossSignUrl = options.crossSignUrl ?? this._networkConfig.crossSignUrl;
83
- }
84
- /**
85
- * Get the current network name.
86
- */
87
- get network() {
88
- return this._network;
89
- }
90
- /**
91
- * Get the cross-sign service URL.
92
- */
93
- get crossSignUrl() {
94
- return this._crossSignUrl;
95
- }
96
- /**
97
- * Get list of supported chain names.
98
- */
99
- get chains() {
100
- return Object.keys(this._networkConfig.chains);
101
- }
102
- /**
103
- * Get configuration for a specific chain.
104
- */
105
- getChainConfig(chain) {
106
- return this._networkConfig.chains[chain] ?? null;
107
- }
108
- /**
109
- * Get token configuration for a chain.
110
- * Handles testUSDC -> USDC normalization for testnet.
111
- */
112
- getTokenConfig(chain, token) {
113
- const chainConfig = this.getChainConfig(chain);
114
- if (!chainConfig)
115
- return null;
116
- // Normalize: testUSDC on Fast testnet maps to USDC on EVM
117
- const lowerToken = token.toLowerCase();
118
- const normalizedToken = lowerToken === 'fastusdc' || lowerToken === 'testusdc' ? 'USDC' : token;
119
- return (chainConfig.tokens[normalizedToken] ??
120
- chainConfig.tokens[normalizedToken.toUpperCase()] ??
121
- null);
122
- }
123
- /**
124
- * Get the full network configuration.
125
- */
126
- getNetworkConfig() {
127
- return this._networkConfig;
128
- }
129
- /**
130
- * Get the raw config (both testnet and mainnet).
131
- */
132
- getRawConfig() {
133
- return this._config;
134
- }
135
- /**
136
- * Deposit tokens from EVM chain to Fast network.
137
- *
138
- * @example
139
- * ```ts
140
- * const result = await allset.sendToFast({
141
- * chain: 'arbitrum-sepolia',
142
- * token: 'USDC',
143
- * amount: '1000000',
144
- * from: '0xYourEvmAddress',
145
- * to: 'fast1receiveraddress',
146
- * evmClients,
147
- * });
148
- * ```
149
- */
150
- async sendToFast(params) {
151
- const normalizedToken = params.token.toLowerCase();
152
- // Map USDC to the correct Fast token: USDC for mainnet, testUSDC for testnet
153
- const fastToken = normalizedToken === 'usdc'
154
- ? (this._network === 'mainnet' ? 'USDC' : 'testUSDC')
155
- : params.token;
156
- const { executeBridge } = await import('./bridge.js');
157
- return executeBridge({
158
- fromChain: params.chain,
159
- toChain: 'fast',
160
- fromToken: params.token,
161
- toToken: fastToken,
162
- fromDecimals: 6,
163
- amount: params.amount,
164
- senderAddress: params.from,
165
- receiverAddress: params.to,
166
- evmClients: params.evmClients,
167
- }, this);
168
- }
169
- /**
170
- * Withdraw tokens from Fast network to EVM chain.
171
- *
172
- * @example
173
- * ```ts
174
- * const result = await allset.sendToExternal({
175
- * chain: 'base',
176
- * token: 'USDC',
177
- * amount: '1000000',
178
- * from: fastWallet.address,
179
- * to: '0xReceiverEvmAddress',
180
- * fastWallet,
181
- * });
182
- * ```
183
- */
184
- async sendToExternal(params) {
185
- const normalizedToken = params.token.toLowerCase();
186
- const { executeBridge } = await import('./bridge.js');
187
- return executeBridge({
188
- fromChain: 'fast',
189
- toChain: params.chain,
190
- fromToken: params.token,
191
- toToken: normalizedToken === 'fastusdc' || normalizedToken === 'testusdc' ? 'USDC' : params.token,
192
- fromDecimals: 6,
193
- amount: params.amount,
194
- senderAddress: params.from,
195
- receiverAddress: params.to,
196
- fastWallet: params.fastWallet,
197
- }, this);
198
- }
199
- /**
200
- * Execute custom intents on an EVM chain.
201
- *
202
- * This is the advanced API for composing custom operations like swaps,
203
- * multi-step transactions, or protocol integrations.
204
- *
205
- * @example
206
- * ```ts
207
- * import { buildTransferIntent, buildExecuteIntent } from '@fastxyz/allset-sdk';
208
- *
209
- * // Simple transfer
210
- * const result = await allset.executeIntent({
211
- * chain: 'base',
212
- * fastWallet, // Compatible Fast wallet, e.g. FastWallet from @fastxyz/sdk
213
- * token: 'USDC',
214
- * amount: '1000000',
215
- * intents: [buildTransferIntent(USDC_ADDRESS, '0xRecipient')],
216
- * });
217
- *
218
- * // Custom contract call
219
- * const result = await allset.executeIntent({
220
- * chain: 'base',
221
- * fastWallet, // Compatible Fast wallet, e.g. FastWallet from @fastxyz/sdk
222
- * token: 'USDC',
223
- * amount: '1000000',
224
- * intents: [buildExecuteIntent(CONTRACT, calldata)],
225
- * externalAddress: CONTRACT,
226
- * });
227
- * ```
228
- */
229
- async executeIntent(params) {
230
- const { executeIntent: execIntent } = await import('./bridge.js');
231
- return execIntent(params, this);
232
- }
233
- }
234
- // ---------------------------------------------------------------------------
235
- // Directory Utilities
236
- // ---------------------------------------------------------------------------
237
- /**
238
- * Get the AllSet home directory (~/.allset).
239
- */
240
- export function getAllSetDir() {
241
- return ALLSET_DIR;
242
- }
243
- /**
244
- * Get the EVM keys directory (~/.allset/.evm/keys).
245
- */
246
- export function getEvmKeysDir() {
247
- return EVM_KEYS_DIR;
248
- }
249
- /**
250
- * Ensure the AllSet directory structure exists.
251
- */
252
- export function ensureAllSetDirs() {
253
- if (!existsSync(ALLSET_DIR)) {
254
- mkdirSync(ALLSET_DIR, { recursive: true, mode: 0o700 });
255
- }
256
- if (!existsSync(EVM_KEYS_DIR)) {
257
- mkdirSync(EVM_KEYS_DIR, { recursive: true, mode: 0o700 });
258
- }
259
- }
260
- /**
261
- * Initialize user config by writing the embedded defaults to ~/.allset/.
262
- * Does nothing if user config already exists.
263
- */
264
- export function initUserConfig() {
265
- ensureAllSetDirs();
266
- const userConfigPath = getUserConfigPath();
267
- if (existsSync(userConfigPath)) {
268
- return userConfigPath;
269
- }
270
- writeFileSync(userConfigPath, `${JSON.stringify(DEFAULT_NETWORKS_CONFIG, null, 2)}\n`, { mode: 0o600 });
271
- return userConfigPath;
272
- }