Skip to content

Commit 7c49a5e

Browse files
authored
Merge pull request #1872 from near/legacy-keystore
feat: add legacy keystore signer
2 parents d0445e4 + 4410317 commit 7c49a5e

2 files changed

Lines changed: 45 additions & 0 deletions

File tree

.changeset/moody-knives-win.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"near-api-js": minor
3+
---
4+
5+
Added a signer that knows how to use the legacy keystore

src/signers/legacy_keystore.ts

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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

Comments
 (0)