-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathEthersV4ContractAdapter.ts
72 lines (63 loc) · 2.02 KB
/
EthersV4ContractAdapter.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
import { Contract } from '../EthLibAdapter'
import EthersAdapter from './'
import {
CallOptions,
SendOptions,
normalizeGasLimit,
EthersTransactionResult
} from '../../utils/transactions'
import { Address } from '../../utils/basicTypes'
class EthersContractAdapter implements Contract {
constructor(public contract: any, public ethersAdapter: EthersAdapter) {}
get address(): Address {
return this.contract.address
}
async call(methodName: string, params: any[], options?: CallOptions): Promise<any> {
const data = this.encode(methodName, params)
const resHex = await this.ethersAdapter.ethCall(
{
...options,
to: this.address,
data
},
'latest'
)
const rets = this.contract.interface.functions[methodName].decode(resHex)
if (rets.length === 1) {
return rets[0]
}
return rets
}
async send(
methodName: string,
params: any[],
options?: SendOptions
): Promise<EthersTransactionResult> {
let transactionResponse
if (options) {
const { from, gas, ...sendOptions } = normalizeGasLimit(options)
await this.ethersAdapter.checkFromAddress(from)
transactionResponse = await this.contract.functions[methodName](...params, {
gasLimit: gas,
...sendOptions
})
} else {
transactionResponse = await this.contract.functions[methodName](...params)
}
return { transactionResponse, hash: transactionResponse.hash }
}
async estimateGas(methodName: string, params: any[], options?: CallOptions): Promise<number> {
if (!options) {
return (await this.contract.estimate[methodName](...params)).toNumber()
} else {
const { gas, ...callOptions } = normalizeGasLimit(options)
return (
await this.contract.estimate[methodName](...params, { gasLimit: gas, ...callOptions })
).toNumber()
}
}
encode(methodName: string, params: any[]): string {
return this.contract.interface.functions[methodName].encode(params)
}
}
export default EthersContractAdapter