|
| 1 | +import fs from 'fs'; |
| 2 | +import os from 'os'; |
| 3 | +import path from 'path'; |
| 4 | +import { KeyPair, type KeyPairString } from '../crypto/index.js'; |
| 5 | +import { KeyPairSigner } from './key_pair_signer.js'; |
| 6 | + |
| 7 | +/** |
| 8 | + * Signs using local credentials stored in the .near-credentials directory. |
| 9 | + * |
| 10 | + * @param accountId - The NEAR account ID for which to load credentials. |
| 11 | + * @param networkId - The NEAR network ID (e.g., "mainnet", "testnet"). Defaults to "testnet". |
| 12 | + * @returns A KeyPairSigner instance initialized with the loaded credentials. |
| 13 | + * @throws Will throw an error if the credentials path or file does not exist, or if the file format is invalid. |
| 14 | + * |
| 15 | + * @example |
| 16 | + * const signer = new LegacyKeyStore("my-account.testnet"); |
| 17 | + * const publicKey = await signer.getPublicKey(); |
| 18 | + * console.log(publicKey.toString()); |
| 19 | + */ |
| 20 | +export class LegacyKeyStoreSigner extends KeyPairSigner { |
| 21 | + constructor(accountId: string, networkId: 'testnet' | 'mainnet' = 'testnet') { |
| 22 | + const localCredentialsPath = path.join(os.homedir(), '.near-credentials', networkId); |
| 23 | + if (!fs.existsSync(localCredentialsPath)) { |
| 24 | + throw new Error(`Credential path does not exist: ${localCredentialsPath}`); |
| 25 | + } |
| 26 | + |
| 27 | + const credentialFile = path.join(localCredentialsPath, `${accountId}.json`); |
| 28 | + if (!fs.existsSync(credentialFile)) { |
| 29 | + throw new Error(`Credentials not found for ${accountId} at path: ${credentialFile}`); |
| 30 | + } |
| 31 | + |
| 32 | + const credentialData = JSON.parse(fs.readFileSync(credentialFile, 'utf-8')); |
| 33 | + if (!credentialData || !credentialData.private_key) { |
| 34 | + throw new Error(`Invalid credential file format at: ${credentialFile}`); |
| 35 | + } |
| 36 | + |
| 37 | + const keyPair = KeyPair.fromString(credentialData.private_key as KeyPairString); |
| 38 | + super(keyPair); |
| 39 | + } |
| 40 | +} |
0 commit comments