-
Notifications
You must be signed in to change notification settings - Fork 20
/
utils.ts
170 lines (153 loc) · 5.28 KB
/
utils.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
import { TypedDataField } from '@ethersproject/abstract-signer'
import { BigNumberish, Contract, providers, Signer, Wallet } from 'ethers'
import { LogDescription, splitSignature } from 'ethers/lib/utils'
import { TransactionReceipt } from '@ethersproject/providers'
import { getConnectionConfig } from '../config/app'
export const loadNetworkConfig = async (signerOrProvider: Signer | providers.Provider) => {
// console.log('provider present', !!signerOrProvider.network || !!signerOrProvider.provider?.network)
const network =
signerOrProvider.network ||
signerOrProvider.provider?.network ||
(await (Signer.isSigner(signerOrProvider)
? signerOrProvider.provider?.getNetwork()
: signerOrProvider.getNetwork()))
const conn = getConnectionConfig(network?.chainId || null)
let networkName = conn.ref
try {
return require(`./deployments/${networkName}/factories-latest.json`)
} catch (e) {
console.log(`no network config for ${networkName}`)
return require('./deployments/mainnet/factories-latest.json')
}
}
export const isPermitable = async (tokenAddress: string) => {
// todo: implement permit token querying
return true
}
export const signPermission = async (
method: string,
vault: Contract,
owner: Wallet,
delegateAddress: string,
tokenAddress: string,
amount: BigNumberish,
vaultNonce?: BigNumberish,
chainId?: BigNumberish,
) => {
// get nonce
vaultNonce = vaultNonce || (await vault.getNonce())
// get chainId
// console.log("provider present", !!vault?.provider?.network)
const network = vault?.provider?.network || (await vault.provider.getNetwork())
chainId = chainId || network.chainId
// craft permission
const domain = {
name: 'UniversalVault',
version: '1.0.0',
chainId,
verifyingContract: vault.address,
}
const types = {} as Record<string, TypedDataField[]>
types[method] = [
{ name: 'delegate', type: 'address' },
{ name: 'token', type: 'address' },
{ name: 'amount', type: 'uint256' },
{ name: 'nonce', type: 'uint256' },
]
const value = {
delegate: delegateAddress,
token: tokenAddress,
amount: amount,
nonce: vaultNonce,
}
// Try to sign with EIP-712
let signedPermission
try {
signedPermission = await owner._signTypedData(domain, types, value)
} catch (error) {
console.log('EIP-712 signing failed, falling back to eth_sign:', error)
// Fallback to eth_sign
const messageHash = ethers.utils._TypedDataEncoder.hash(domain, types, value)
signedPermission = await owner.provider.send('eth_sign', [owner.address, messageHash])
}
const replaceV: any = []
replaceV['00'] = '1b'
replaceV['01'] = '1c'
let signedPermissionNew
if (replaceV[signedPermission.slice(-2)]) {
signedPermissionNew = signedPermission.slice(0, signedPermission.length - 2) + replaceV[signedPermission.slice(-2)]
} else {
signedPermissionNew = signedPermission
}
return signedPermissionNew
}
export const signPermitEIP2612 = async (
owner: Wallet,
token: Contract,
spenderAddress: string,
value: BigNumberish,
deadline: BigNumberish,
nonce?: BigNumberish,
) => {
// get nonce
nonce = nonce || (await token.nonces(owner.address))
// get domain
const domainSeparator = await token.DOMAIN_SEPARATOR()
// get types
const types = {} as Record<string, TypedDataField[]>
types['Permit'] = [
{ name: 'owner', type: 'address' },
{ name: 'spender', type: 'address' },
{ name: 'value', type: 'uint256' },
{ name: 'nonce', type: 'uint256' },
{ name: 'deadline', type: 'uint256' },
]
// get values
const values = {
owner: owner.address,
spender: spenderAddress,
value: value,
nonce: nonce,
deadline: deadline,
}
// Try to sign with EIP-712
let signedPermission
try {
signedPermission = await owner._signTypedData(domainSeparator, types, values)
} catch (error) {
console.log('EIP-712 signing failed, falling back to eth_sign:', error)
// Fallback to eth_sign
const messageHash = ethers.utils._TypedDataEncoder.hash(
{ chainId: await token.provider.getNetwork().chainId, ...domainSeparator },
types,
values,
)
signedPermission = await owner.provider.send('eth_sign', [owner.address, messageHash])
}
// split signature
const sig = splitSignature(signedPermission)
// return
return [values.owner, values.spender, values.value, values.deadline, sig.v, sig.r, sig.s]
}
// utility function to parse an event from a transaction receipt
// useful when we need to get data from a specific transaction (e.g. getting the actual rewards claimed from unstake)
export const parseFirstEventFromReceipt = (
receipt: TransactionReceipt,
contract: Contract,
event: string,
): LogDescription | null => {
const events = parseAllEventsFromReceipt(receipt, contract, event)
return events.length > 0 ? events[0] : null
}
export const parseAllEventsFromReceipt = (
receipt: TransactionReceipt,
contract: Contract,
event: string,
): LogDescription[] => {
const filter = contract.filters[event]
if (!filter) return []
const eventFilter = filter()
if (!eventFilter || !eventFilter.topics || eventFilter.topics.length === 0) return []
const topicHash = eventFilter.topics[0]
return receipt.logs.filter((log) => log.topics[0] === topicHash).map((l) => contract.interface.parseLog(l))
}