forked from saber-hq/saber-common
/
TransactionReceipt.ts
104 lines (95 loc) 路 2.63 KB
/
TransactionReceipt.ts
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
94
95
96
97
98
99
100
101
102
103
104
import type {
Cluster,
TransactionResponse,
TransactionSignature,
VersionedTransactionResponse,
} from "@solana/web3.js";
import { default as invariant } from "tiny-invariant";
import type { Event, EventParser } from "../interfaces.js";
import type { PromiseOrValue } from "../utils/misc.js";
import { valueAsPromise } from "../utils/misc.js";
import { generateTXLink } from "../utils/txLink.js";
import { PendingTransaction } from "./PendingTransaction.js";
import type { TransactionEnvelope } from "./TransactionEnvelope.js";
/**
* A value that can be processed into a {@link TransactionReceipt}.
*/
export type TransactionLike =
| TransactionEnvelope
| PendingTransaction
| TransactionReceipt;
/**
* Confirms a transaction, returning its receipt.
*
* @param tx
* @returns
*/
export const confirmTransactionLike = async (
tx: PromiseOrValue<TransactionLike>
): Promise<TransactionReceipt> => {
const ish = await valueAsPromise(tx);
if (ish instanceof TransactionReceipt) {
return ish;
}
let pending: PendingTransaction;
if (ish instanceof PendingTransaction) {
pending = ish;
} else {
pending = await ish.send({
printLogs: false,
});
}
return await pending.wait();
};
/**
* A transaction that has been processed by the cluster.
*/
export class TransactionReceipt {
constructor(
/**
* Signature (id) of the transaction.
*/
readonly signature: TransactionSignature,
/**
* Raw response from web3.js
*/
readonly response: TransactionResponse | VersionedTransactionResponse
) {}
/**
* Gets the events associated with this transaction.
*/
getEvents<E extends Event>(eventParser: EventParser<E>): readonly E[] {
const logs = this.response.meta?.logMessages;
if (logs && logs.length > 0) {
return eventParser(logs);
}
return [];
}
/**
* Prints the logs associated with this transaction.
*/
printLogs(): void {
console.log(this.response.meta?.logMessages?.join("\n"));
}
/**
* Gets the compute units used by the transaction.
* @returns
*/
get computeUnits(): number {
const logs = this.response.meta?.logMessages;
invariant(logs, "no logs");
const consumeLog = logs[logs.length - 2];
invariant(consumeLog, "no consume log");
const amtStr = consumeLog.split(" ")[3];
invariant(amtStr, "no amount");
return parseInt(amtStr);
}
/**
* Generates a link to view this {@link TransactionReceipt} on the official Solana explorer.
* @param network
* @returns
*/
generateSolanaExplorerLink(cluster: Cluster = "mainnet-beta"): string {
return generateTXLink(this.signature, cluster);
}
}