-
Notifications
You must be signed in to change notification settings - Fork 115
/
Copy pathmetamask.wallet.provider.ts
305 lines (292 loc) Β· 12 KB
/
metamask.wallet.provider.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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
import { BigNumber } from 'bignumber.js'
import { TatumConnector } from '../../../connector/tatum.connector'
import { EVM_BASED_NETWORKS, Network, TxPayload } from '../../../dto'
import {
CreateErc1155NftCollection,
CreateFungibleToken,
CreateNftCollection,
} from '../../../dto/walletProvider'
import { Logger } from '../../../service/logger/logger.types'
import { Constant, EnvUtils, Utils } from '../../../util'
import { ITatumSdkContainer, TatumSdkWalletProvider } from '../../extensions'
import { EvmRpc } from '../../rpc'
import { TatumConfig } from '../../tatum'
export class MetaMask extends TatumSdkWalletProvider<string, TxPayload> {
supportedNetworks: Network[] = EVM_BASED_NETWORKS
private readonly config: TatumConfig
private readonly rpc: EvmRpc
private readonly connector: TatumConnector
private readonly logger: Logger
constructor(tatumSdkContainer: ITatumSdkContainer) {
super(tatumSdkContainer)
this.config = this.tatumSdkContainer.getConfig()
this.rpc = this.tatumSdkContainer.get(EvmRpc)
this.connector = this.tatumSdkContainer.get(TatumConnector)
this.logger = this.tatumSdkContainer.getLogger()
}
/**
* Connect to MetaMask wallet. this method checks if MetaMask is installed and if it is connected to the browser.
* If so, it returns the address of the connected account. If not, it throws an error.
* @returns address of the connected account.
*/
async getWallet(): Promise<string> {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
if (typeof window.ethereum === 'undefined') {
this.logger.error('MetaMask is not installed or its impossible to connect to it.')
throw new Error('MetaMask is not installed or its impossible to connect to it.')
}
if (EnvUtils.isDevelopment()) {
this.logger.info(
'You can get FREE testnet tokens to test your contracts on any number of chains: https://co.tatum.io/faucets',
)
}
try {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' })
return accounts[0] as string
} catch (error) {
this.logger.error('User denied account access:', error)
throw new Error(`User denied account access. Error is ${error}`)
}
}
/**
* Sign native transaction with MetaMask wallet. This method checks if MetaMask is installed and if it is connected to the browser.
* If so, it returns the signed transaction hash. If not, it throws an error.
* @param recipient recipient of the transaction
* @param amount amount to be sent, in native currency (ETH, BSC)
*/
async transferNative(recipient: string, amount: string): Promise<string> {
const payload: TxPayload = {
to: recipient,
from: await this.getWallet(),
value: `0x${new BigNumber(amount)
.multipliedBy(10 ** Constant.DECIMALS[this.config.network])
.toString(16)}`,
}
try {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
// eslint-disable-next-line @typescript-eslint/return-await
return await window.ethereum.request({
method: 'eth_sendTransaction',
params: [payload],
})
} catch (e) {
this.logger.error('User denied transaction signature:', e)
throw new Error(`User denied transaction signature. Error is ${e}`)
}
}
/**
* Sign ERC-20 fungible token `transfer` transaction (https://ethereum.org/en/developers/docs/standards/tokens/erc-20/#methods) with MetaMask wallet. This method checks if MetaMask is installed and if it is connected to the browser.
* If so, it returns the signed transaction hash. If not, it throws an error.
* @param recipient recipient of the transaction
* @param amount amount to be sent, in token currency
* @param tokenAddress address of the token contract
*/
async transferErc20(recipient: string, amount: string, tokenAddress: string): Promise<string> {
const { result: decimals } = await this.rpc.getTokenDecimals(tokenAddress)
const payload: TxPayload = {
to: tokenAddress,
from: await this.getWallet(),
data: `0xa9059cbb${Utils.padWithZero(recipient)}${new BigNumber(amount)
.multipliedBy(10 ** decimals!.toNumber())
.toString(16)
.padStart(64, '0')}`,
}
try {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
// eslint-disable-next-line @typescript-eslint/return-await
return await window.ethereum.request({
method: 'eth_sendTransaction',
params: [payload],
})
} catch (e) {
this.logger.error('User denied transaction signature:', e)
throw new Error(`User denied transaction signature. Error is ${e}`)
}
}
/**
* Deploy new ERC-721 NFT Collection contract with MetaMask wallet. This method checks if MetaMask is installed and if it is connected to the browser.
* If so, it returns the signed transaction hash. If not, it throws an error.
*/
async createNftCollection(body: CreateNftCollection): Promise<string> {
const { name, symbol, baseURI, author, minter } = body
const from = await this.getWallet()
const { data } = await this.connector.post<{ data: string }>({
path: `contract/deploy/prepare`,
body: {
contractType: 'nft',
params: [name, symbol, baseURI || '', author || from, minter || from],
},
})
const payload: TxPayload = {
from: from,
data,
}
try {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
// eslint-disable-next-line @typescript-eslint/return-await
return await window.ethereum.request({
method: 'eth_sendTransaction',
params: [payload],
})
} catch (e) {
this.logger.error('User denied transaction signature:', e)
throw new Error(`User denied transaction signature. Error is ${e}`)
}
}
/**
* Deploy new ERC-20 Token (USDT or USDC like) contract with MetaMask wallet. This method checks if MetaMask is installed and if it is connected to the browser.
* If so, it returns the signed transaction hash. If not, it throws an error.
*/
async createFungibleToken(body: CreateFungibleToken): Promise<string> {
const from = await this.getWallet()
const decimals = body.decimals || 18
const { data } = await this.connector.post<{ data: string }>({
path: `contract/deploy/prepare`,
body: {
contractType: 'fungible',
params: [
body.name,
body.symbol,
decimals,
`0x${new BigNumber(body.initialSupply).multipliedBy(10 ** decimals).toString(16)}`,
body.initialHolder || from,
body.admin || from,
body.minter || from,
body.pauser || from,
],
},
})
const payload: TxPayload = {
from: from,
data,
}
try {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
// eslint-disable-next-line @typescript-eslint/return-await
return await window.ethereum.request({
method: 'eth_sendTransaction',
params: [payload],
})
} catch (e) {
this.logger.error('User denied transaction signature:', e)
throw new Error(`User denied transaction signature. Error is ${e}`)
}
}
/**
* Deploy new ERC-1155 NFT Collection contract with MetaMask wallet. This method checks if MetaMask is installed and if it is connected to the browser.
* If so, it returns the signed transaction hash. If not, it throws an error.
*/
async createErc1155NftCollection(body?: CreateErc1155NftCollection): Promise<string> {
const { author, minter, baseURI } = body || {}
const from = await this.getWallet()
const { data } = await this.connector.post<{ data: string }>({
path: `contract/deploy/prepare`,
body: {
contractType: 'multitoken',
params: [author || from, minter || from, baseURI || ''],
},
})
const payload: TxPayload = {
from: from,
data,
}
try {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
// eslint-disable-next-line @typescript-eslint/return-await
return await window.ethereum.request({
method: 'eth_sendTransaction',
params: [payload],
})
} catch (e) {
this.logger.error('User denied transaction signature:', e)
throw new Error(`User denied transaction signature. Error is ${e}`)
}
}
/**
* Sign ERC-721 non-fungible token `safeTransferFrom` transaction (https://ethereum.org/en/developers/docs/standards/tokens/erc-721/#methods) with MetaMask wallet. This method checks if MetaMask is installed and if it is connected to the browser.
* If so, it returns the signed transaction hash. If not, it throws an error.
* @param recipient recipient of the transaction
* @param tokenId ID of the NFT token
* @param tokenAddress address of the token contract
*/
async transferNft(recipient: string, tokenId: string, tokenAddress: string): Promise<string> {
const from = await this.getWallet()
const payload: TxPayload = {
to: tokenAddress,
from: from,
data: `0x42842e0e${Utils.padWithZero(from)}${Utils.padWithZero(recipient)}${new BigNumber(tokenId)
.toString(16)
.padStart(64, '0')}`,
}
try {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
// eslint-disable-next-line @typescript-eslint/return-await
return await window.ethereum.request({
method: 'eth_sendTransaction',
params: [payload],
})
} catch (e) {
this.logger.error('User denied transaction signature:', e)
throw new Error(`User denied transaction signature. Error is ${e}`)
}
}
/**
* Sign ERC-20 fungible token `approve` transaction (https://ethereum.org/en/developers/docs/standards/tokens/erc-20/#methods) with MetaMask wallet. This method checks if MetaMask is installed and if it is connected to the browser.
* If so, it returns the signed transaction hash. If not, it throws an error.
* @param spender address to be approved to spend the tokens
* @param amount amount to be sent, in token currency
* @param tokenAddress address of the token contract
*/
async approveErc20(spender: string, amount: string, tokenAddress: string): Promise<string> {
const { result: decimals } = await this.rpc.getTokenDecimals(tokenAddress)
const payload: TxPayload = {
to: tokenAddress,
from: await this.getWallet(),
data: `0x095ea7b3${Utils.padWithZero(spender)}${new BigNumber(amount)
.multipliedBy(10 ** decimals!.toNumber())
.toString(16)
.padStart(64, '0')}`,
}
try {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
// eslint-disable-next-line @typescript-eslint/return-await
return await window.ethereum.request({
method: 'eth_sendTransaction',
params: [payload],
})
} catch (e) {
this.logger.error('User denied transaction signature:', e)
throw new Error(`User denied transaction signature. Error is ${e}`)
}
}
/**
* Sign custom transaction with MetaMask wallet. This method checks if MetaMask is installed and if it is connected to the browser.
* If so, it returns the signed transaction hash. If not, it throws an error.
* @param payload Transaction payload. From field is ignored and will be overwritten by the connected account.
*/
async signAndBroadcast(payload: TxPayload): Promise<string> {
payload.from = await this.getWallet()
try {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
// eslint-disable-next-line @typescript-eslint/return-await
return await window.ethereum.request({
method: 'eth_sendTransaction',
params: [payload],
})
} catch (e) {
this.logger.error('User denied transaction signature:', e)
throw new Error(`User denied transaction signature. Error is ${e}`)
}
}
}