forked from StellarRouter/StellarRouter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsigner.ts
More file actions
93 lines (82 loc) · 2.66 KB
/
Copy pathsigner.ts
File metadata and controls
93 lines (82 loc) · 2.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import { Keypair, Networks, Transaction, TransactionBuilder } from "@stellar/stellar-sdk";
import { RouterSdkError } from "./errors.js";
/**
* Signing abstraction (see `docs/signing-abstraction.md`).
*
* Implementations may return the public key synchronously (an in-memory
* keypair) or asynchronously (a wallet extension).
*/
export interface Signer {
/** The Stellar public key (`G...`) that authenticates transactions. */
publicKey(): string | Promise<string>;
/** Return `transaction` signed by this signer. */
sign(transaction: Transaction): Promise<Transaction>;
}
/**
* Signs with an in-memory Stellar {@link Keypair}.
*/
export class LocalSigner implements Signer {
readonly keypair: Keypair;
constructor(keypair: Keypair) {
this.keypair = keypair;
}
publicKey(): string {
return this.keypair.publicKey();
}
async sign(transaction: Transaction): Promise<Transaction> {
try {
transaction.sign(this.keypair);
return transaction;
} catch (cause) {
throw new RouterSdkError(
"SigningFailed",
"Failed to sign the transaction with the provided keypair.",
{ contract: "core", cause },
);
}
}
}
/** Options for {@link FreighterSigner}. */
export interface FreighterSignerOptions {
/** Network passphrase used to parse the signed transaction XDR. */
networkPassphrase?: string;
}
/**
* Delegates signing to the Freighter browser extension.
*
* The module is loaded lazily via dynamic `import`, so the package can be
* used in Node without installing `@stellar/freighter-api`.
*/
export class FreighterSigner implements Signer {
private readonly networkPassphrase: string;
constructor(options: FreighterSignerOptions = {}) {
this.networkPassphrase = options.networkPassphrase ?? Networks.TESTNET;
}
async publicKey(): Promise<string> {
try {
const { getPublicKey } = await import("@stellar/freighter-api");
return await getPublicKey();
} catch (cause) {
throw new RouterSdkError(
"SigningFailed",
"Failed to read the public key from Freighter. Is the extension unlocked?",
{ cause },
);
}
}
async sign(transaction: Transaction): Promise<Transaction> {
try {
const { signTransaction } = await import("@stellar/freighter-api");
const signedXdr = await signTransaction(transaction.toXDR(), {
networkPassphrase: this.networkPassphrase,
});
return TransactionBuilder.fromXDR(signedXdr, this.networkPassphrase) as Transaction;
} catch (cause) {
throw new RouterSdkError(
"SigningFailed",
"Failed to sign the transaction with Freighter.",
{ cause },
);
}
}
}