/
abstract.ts
186 lines (167 loc) · 5.58 KB
/
abstract.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
import { EVMWallet } from "../interfaces";
import type { Signer } from "ethers";
import { utils, Bytes, BigNumber } from "ethers";
import EventEmitter from "eventemitter3";
import { Ecosystem, GenericAuthWallet } from "../../core/interfaces/auth";
import {
NATIVE_TOKEN_ADDRESS,
Price,
TransactionResult,
fetchCurrencyValue,
getDefaultGasOverrides,
isNativeToken,
normalizePriceValue,
} from "@thirdweb-dev/sdk";
import { createErc20 } from "../utils/currency";
// TODO improve this
export function chainIdToThirdwebRpc(chainId: number, clientId?: string) {
return `https://${chainId}.rpc.thirdweb.com${clientId ? `/${clientId}` : ""}${
typeof globalThis !== "undefined" && "APP_BUNDLE_ID" in globalThis && !!(globalThis as any).APP_BUNDLE_ID
? `?bundleId=${(globalThis as any).APP_BUNDLE_ID as string}`
: ""
}`;
}
export type WalletData = {
address?: string;
chainId?: number;
};
export interface WalletEvents {
connect(data: WalletData): void;
change(data: WalletData): void;
message({ type, data }: { type: string; data?: unknown }): void;
disconnect(): void;
error(error: Error): void;
display_uri(uri: string): void;
wc_session_request_sent(): void;
request(): void;
}
/**
* The base class for any wallet in the Wallet SDK, including backend wallets. It contains the functionality common to all wallets.
*
* This wallet is not meant to be used directly, but instead be extended to [build your own wallet](https://portal.thirdweb.com/wallet-sdk/v2/build)
*
* @abstractWallet
*/
export abstract class AbstractWallet
extends EventEmitter<WalletEvents>
implements GenericAuthWallet, EVMWallet
{
/**
* @internal
*/
public type: Ecosystem = "evm";
/**
* Returns an [ethers Signer](https://docs.ethers.org/v5/api/signer/) object of the connected wallet
*/
public abstract getSigner(): Promise<Signer>;
/**
* Returns the account address of the connected wallet
*/
public async getAddress(): Promise<string> {
const signer = await this.getSigner();
return signer.getAddress();
}
/**
* Returns the balance of the connected wallet for the specified token address. If no token address is specified, it returns the balance of the native token
*
* @param tokenAddress - The contract address of the token
*/
public async getBalance(tokenAddress: string = NATIVE_TOKEN_ADDRESS) {
const signer = await this.getSigner();
const address = await this.getAddress();
if (!signer.provider) {
throw new Error("Please connect a provider");
}
let balance: BigNumber;
if (isNativeToken(tokenAddress)) {
balance = await signer.provider.getBalance(address);
} else {
const erc20 = createErc20(signer, tokenAddress);
balance = await erc20.balanceOf(address);
}
// Note: assumes that the native currency decimals is 18, which isn't always correct
return await fetchCurrencyValue(signer.provider, tokenAddress, balance);
}
/**
* Returns the chain id of the network that the wallet is connected to
*/
public async getChainId(): Promise<number> {
const signer = await this.getSigner();
return signer.getChainId();
}
/**
* Transfers some amount of tokens to the specified address
* @param to - The address to transfer the amount to
* @param amount - The amount to transfer
* @param currencyAddress - The contract address of the token to transfer. If not specified, it defaults to the native token
* @returns The transaction result
*/
public async transfer(
to: string,
amount: Price,
currencyAddress: string = NATIVE_TOKEN_ADDRESS,
): Promise<TransactionResult> {
const signer = await this.getSigner();
const from = await this.getAddress();
if (!signer.provider) {
throw new Error("Please connect a provider");
}
const value = await normalizePriceValue(
signer.provider,
amount,
currencyAddress,
);
if (isNativeToken(currencyAddress)) {
const gas = getDefaultGasOverrides(signer.provider);
const tx = await signer.sendTransaction({
from,
to,
value,
...gas,
});
return { receipt: await tx.wait() };
} else {
const erc20 = createErc20(signer, currencyAddress);
const tx = await erc20.transfer(to, value);
return { receipt: await tx.wait() };
}
}
/**
* Sign a message with the connected wallet and return the signature
* @param message - The message to sign
* @returns - The signature
*/
public async signMessage(message: Bytes | string): Promise<string> {
const signer = await this.getSigner();
return await signer.signMessage(message);
}
/**
* Verify the signature of a message. It returns `true` if the signature is valid, `false` otherwise
* @param message - The message to verify
* @param signature - The signature to verify
* @param address - The address to verify the signature against
* @param chainId - The chain id of the network to verify the signature against, If not specified, it defaults to 1 ( Ethereum mainnet )
*/
public async verifySignature(
message: string,
signature: string,
address: string,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
_chainId?: number,
): Promise<boolean> {
try {
const messageHash = utils.hashMessage(message);
const messageHashBytes = utils.arrayify(messageHash);
const recoveredAddress = utils.recoverAddress(
messageHashBytes,
signature,
);
if (recoveredAddress === address) {
return true;
}
} catch {
// no-op
}
return false;
}
}