This repository has been archived by the owner on Oct 24, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 78
/
Copy pathkashipair.js
477 lines (440 loc) · 18.1 KB
/
kashipair.js
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
const ethers = require("ethers")
const {
utils: { keccak256, defaultAbiCoder },
} = require("ethers")
const { ecsign } = require("ethereumjs-util")
function addr(address) {
if (typeof address == "object" && address.address) {
address = address.address
}
return address
}
const BENTOBOX_MASTER_APPROVAL_TYPEHASH = keccak256(
ethers.utils.toUtf8Bytes("SetMasterContractApproval(string warning,address user,address masterContract,bool approved,uint256 nonce)")
)
function getBentoBoxDomainSeparator(address, chainId) {
return keccak256(
defaultAbiCoder.encode(
["bytes32", "bytes32", "uint256", "address"],
[
keccak256(ethers.utils.toUtf8Bytes("EIP712Domain(string name,uint256 chainId,address verifyingContract)")),
keccak256(ethers.utils.toUtf8Bytes("BentoBox V1")),
chainId,
address,
]
)
)
}
function getBentoBoxApprovalDigest(bentoBox, user, masterContractAddress, approved, nonce, chainId = 1) {
const DOMAIN_SEPARATOR = getBentoBoxDomainSeparator(bentoBox.address, chainId)
const msg = defaultAbiCoder.encode(
["bytes32", "bytes32", "address", "address", "bool", "uint256"],
[
BENTOBOX_MASTER_APPROVAL_TYPEHASH,
keccak256(ethers.utils.toUtf8Bytes(approved ? "Give FULL access to funds in (and approved to) BentoBox?" : "Revoke access to BentoBox?")),
user.address,
masterContractAddress,
approved,
nonce,
]
)
const pack = ethers.utils.solidityPack(["bytes1", "bytes1", "bytes32", "bytes32"], ["0x19", "0x01", DOMAIN_SEPARATOR, keccak256(msg)])
return keccak256(pack)
}
function getSignedMasterContractApprovalData(bentoBox, user, privateKey, masterContractAddress, approved, nonce) {
const digest = getBentoBoxApprovalDigest(bentoBox, user, masterContractAddress, approved, nonce, user.provider._network.chainId)
const { v, r, s } = ecsign(Buffer.from(digest.slice(2), "hex"), Buffer.from(privateKey.replace("0x", ""), "hex"))
return { v, r, s }
}
const ERC20abi = [
{
anonymous: false,
inputs: [
{ indexed: true, internalType: "address", name: "_owner", type: "address" },
{ indexed: true, internalType: "address", name: "_spender", type: "address" },
{ indexed: false, internalType: "uint256", name: "_value", type: "uint256" },
],
name: "Approval",
type: "event",
},
{
anonymous: false,
inputs: [
{ indexed: true, internalType: "address", name: "_from", type: "address" },
{ indexed: true, internalType: "address", name: "_to", type: "address" },
{ indexed: false, internalType: "uint256", name: "_value", type: "uint256" },
],
name: "Transfer",
type: "event",
},
{
inputs: [],
name: "DOMAIN_SEPARATOR",
outputs: [{ internalType: "bytes32", name: "", type: "bytes32" }],
stateMutability: "view",
type: "function",
},
{
inputs: [
{ internalType: "address", name: "", type: "address" },
{ internalType: "address", name: "", type: "address" },
],
name: "allowance",
outputs: [{ internalType: "uint256", name: "", type: "uint256" }],
stateMutability: "view",
type: "function",
},
{
inputs: [
{ internalType: "address", name: "spender", type: "address" },
{ internalType: "uint256", name: "amount", type: "uint256" },
],
name: "approve",
outputs: [{ internalType: "bool", name: "success", type: "bool" }],
stateMutability: "nonpayable",
type: "function",
},
{
inputs: [{ internalType: "address", name: "", type: "address" }],
name: "balanceOf",
outputs: [{ internalType: "uint256", name: "", type: "uint256" }],
stateMutability: "view",
type: "function",
},
{
inputs: [{ internalType: "address", name: "", type: "address" }],
name: "nonces",
outputs: [{ internalType: "uint256", name: "", type: "uint256" }],
stateMutability: "view",
type: "function",
},
{
inputs: [
{ internalType: "address", name: "owner_", type: "address" },
{ internalType: "address", name: "spender", type: "address" },
{ internalType: "uint256", name: "value", type: "uint256" },
{ internalType: "uint256", name: "deadline", type: "uint256" },
{ internalType: "uint8", name: "v", type: "uint8" },
{ internalType: "bytes32", name: "r", type: "bytes32" },
{ internalType: "bytes32", name: "s", type: "bytes32" },
],
name: "permit",
outputs: [],
stateMutability: "nonpayable",
type: "function",
},
{
inputs: [
{ internalType: "address", name: "to", type: "address" },
{ internalType: "uint256", name: "amount", type: "uint256" },
],
name: "transfer",
outputs: [{ internalType: "bool", name: "success", type: "bool" }],
stateMutability: "nonpayable",
type: "function",
},
{
inputs: [
{ internalType: "address", name: "from", type: "address" },
{ internalType: "address", name: "to", type: "address" },
{ internalType: "uint256", name: "amount", type: "uint256" },
],
name: "transferFrom",
outputs: [{ internalType: "bool", name: "success", type: "bool" }],
stateMutability: "nonpayable",
type: "function",
},
]
// Functions that need accrue to be called
const ACTION_ADD_ASSET = 1;
const ACTION_REPAY = 2;
const ACTION_REMOVE_ASSET = 3;
const ACTION_REMOVE_COLLATERAL = 4;
const ACTION_BORROW = 5;
const ACTION_GET_REPAY_SHARE = 6;
const ACTION_GET_REPAY_PART = 7;
// Functions that don't need accrue to be called
const ACTION_ADD_COLLATERAL = 10;
// Function on BentoBox
const ACTION_BENTO_DEPOSIT = 20;
const ACTION_BENTO_WITHDRAW = 21;
const ACTION_BENTO_TRANSFER = 22;
const ACTION_BENTO_TRANSFER_MULTIPLE = 23;
const ACTION_BENTO_SETAPPROVAL = 24;
// Any external call (except to BentoBox)
const ACTION_CALL = 30;
class KashiPair {
constructor(contract, helper) {
this.contract = contract
this.helper = helper
this.address = contract.address
}
async init(bentoBox) {
this.bentoBox = bentoBox
this.asset = new ethers.Contract(await this.contract.asset(), ERC20abi, this.contract.signer)
this.collateral = new ethers.Contract(await this.contract.collateral(), ERC20abi, this.contract.signer)
return this
}
as(from) {
let connectedPair = new KashiPair(this.contract.connect(from))
connectedPair.bentoBox = this.bentoBox.connect(from)
connectedPair.helper = this.helper
connectedPair.asset = this.asset.connect(from)
connectedPair.collateral = this.collateral.connect(from)
return connectedPair
}
async run(commandsFunction) {
const commands = commandsFunction(this.cmd)
for (let i = 0; i < commands.length; i++) {
if (typeof commands[i] == "object" && commands[i].type == "KashiPairCmd") {
//console.log("RUN CMD: ", commands[i].method, commands[i].params, commands[i].as ? commands[i].as.address : "")
let pair = commands[i].pair
if (commands[i].as) {
pair = await pair.as(commands[i].as)
}
let tx = await pair[commands[i].method](...commands[i].params)
let receipt = await tx.wait()
//console.log("Gas used: ", receipt.gasUsed.toString());
} else if (typeof commands[i] == "object" && commands[i].type == "KashiPairDo") {
//console.log("RUN DO: ", commands[i].method, commands[i].params)
await commands[i].method(...commands[i].params)
} else {
//console.log("RUN: ", commands[i])
await commands[i]
}
}
}
getDomainSeparator(tokenAddress, chainId) {
return keccak256(
defaultAbiCoder.encode(
["bytes32", "uint256", "address"],
[keccak256(ethers.utils.toUtf8Bytes("EIP712Domain(uint256 chainId,address verifyingContract)")), chainId, tokenAddress]
)
)
}
getApprovalDigest(token, approve, nonce, deadline, chainId = 1) {
const PERMIT_TYPEHASH = keccak256(
ethers.utils.toUtf8Bytes("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)")
)
const DOMAIN_SEPARATOR = this.getDomainSeparator(token.address, chainId)
const msg = defaultAbiCoder.encode(
["bytes32", "address", "address", "uint256", "uint256", "uint256"],
[PERMIT_TYPEHASH, approve.owner, approve.spender, approve.value, nonce, deadline]
)
const pack = ethers.utils.solidityPack(["bytes1", "bytes1", "bytes32", "bytes32"], ["0x19", "0x01", DOMAIN_SEPARATOR, keccak256(msg)])
return keccak256(pack)
}
tokenPermit(token, owner, owner_key, amount, nonce, deadline) {
const digest = this.getApprovalDigest(
token,
{
owner: addr(owner),
spender: addr(this.bentoBox),
value: amount,
},
nonce,
deadline,
owner.provider._network.chainId
)
const { v, r, s } = ecsign(Buffer.from(digest.slice(2), "hex"), Buffer.from(owner_key.replace("0x", ""), "hex"))
//return token.permit(addr(owner), addr(this.bentoBox), amount, deadline, v, r, s);
let data = token.interface.encodeFunctionData("permit", [addr(owner), addr(this.bentoBox), amount, deadline, v, r, s])
return this.contract.cook(
[ACTION_CALL],
[0],
[defaultAbiCoder.encode(["address", "bytes", "bool", "bool", "uint8"], [addr(token), data, false, false, 0])]
)
}
approveAsset(amount) {
return this.asset.approve(this.bentoBox.address, amount)
}
approveCollateral(amount) {
return this.collateral.approve(this.bentoBox.address, amount)
}
depositCollateral(amount) {
return this.contract.cook(
[ACTION_BENTO_DEPOSIT, ACTION_ADD_COLLATERAL],
[0, 0],
[
defaultAbiCoder.encode(
["address", "address", "int256", "int256"],
[this.collateral.address, addr(this.contract.signer), amount, 0]
),
defaultAbiCoder.encode(["int256", "address", "bool"], [-2, addr(this.contract.signer), false]),
]
)
}
withdrawCollateral(share) {
return this.contract.cook(
[ACTION_REMOVE_COLLATERAL, ACTION_BENTO_WITHDRAW],
[0, 0],
[
defaultAbiCoder.encode(["int256", "address"], [share, addr(this.contract.signer)]),
defaultAbiCoder.encode(
["address", "address", "int256", "int256"],
[this.collateral.address, addr(this.contract.signer), 0, share]
),
]
)
}
depositAssetWithApproval(amount, masterContract, privateKey, nonce) {
const { v, r, s } = getSignedMasterContractApprovalData(
this.bentoBox,
this.contract.signer,
privateKey,
addr(masterContract),
true,
nonce
)
return this.contract.cook(
[ACTION_BENTO_SETAPPROVAL, ACTION_BENTO_DEPOSIT, ACTION_ADD_ASSET],
[0, 0, 0],
[
defaultAbiCoder.encode(
["address", "address", "bool", "uint8", "bytes32", "bytes32"],
[addr(this.contract.signer), addr(masterContract), true, v, r, s]
),
defaultAbiCoder.encode(["address", "address", "int256", "int256"], [this.asset.address, addr(this.contract.signer), amount, 0]),
defaultAbiCoder.encode(["int256", "address", "bool"], [-2, addr(this.contract.signer), false]),
]
)
}
depositAsset(amount) {
return this.contract.cook(
[ACTION_BENTO_DEPOSIT, ACTION_ADD_ASSET],
[0, 0],
[
defaultAbiCoder.encode(["address", "address", "int256", "int256"], [this.asset.address, addr(this.contract.signer), amount, 0]),
defaultAbiCoder.encode(["int256", "address", "bool"], [-2, addr(this.contract.signer), false]),
]
)
}
withdrawAsset(fraction) {
return this.contract.cook(
[ACTION_REMOVE_ASSET, ACTION_BENTO_WITHDRAW],
[0, 0],
[
defaultAbiCoder.encode(["int256", "address"], [fraction, addr(this.contract.signer)]),
defaultAbiCoder.encode(["address", "address", "int256", "int256"], [this.asset.address, addr(this.contract.signer), 0, -1]),
]
)
}
repay(part) {
return this.contract.cook(
[ACTION_GET_REPAY_SHARE, ACTION_BENTO_DEPOSIT, ACTION_REPAY],
[0, 0, 0],
[
defaultAbiCoder.encode(["int256"], [part]),
defaultAbiCoder.encode(["address", "address", "int256", "int256"], [this.asset.address, addr(this.contract.signer), 0, -1]),
defaultAbiCoder.encode(["int256", "address", "bool"], [part, addr(this.contract.signer), false]),
]
)
}
repayFromBento(part) {
return this.contract.repay(addr(this.contract.signer), false, part)
}
borrow(amount) {
return this.contract.cook(
[ACTION_BORROW, ACTION_BENTO_WITHDRAW],
[0, 0],
[
defaultAbiCoder.encode(["uint256", "address"], [amount, addr(this.contract.signer)]),
defaultAbiCoder.encode(["address", "address", "int256", "int256"], [this.asset.address, addr(this.contract.signer), 0, -2]),
]
)
}
short(swapper, amount, minReturnedShare) {
let data = swapper.interface.encodeFunctionData("swap", [
this.asset.address,
this.collateral.address,
addr(this.contract.signer),
minReturnedShare,
"0",
])
return this.contract.cook(
[ACTION_BORROW, ACTION_BENTO_TRANSFER, ACTION_CALL, ACTION_ADD_COLLATERAL],
[0, 0, 0, 0, 0],
[
defaultAbiCoder.encode(["int256", "address"], [amount, addr(this.contract.signer)]),
defaultAbiCoder.encode(["address", "address", "int256"], [this.asset.address, swapper.address, -2]),
defaultAbiCoder.encode(["address", "bytes", "bool", "bool", "uint8"], [swapper.address, data.slice(0, -64), false, true, 2]),
defaultAbiCoder.encode(["int256", "address", "bool"], [-2, addr(this.contract.signer), false]),
]
)
}
unwind(swapper, part, maxShare) {
let data = swapper.interface.encodeFunctionData("swapExact", [
this.collateral.address,
this.asset.address,
addr(this.contract.signer),
addr(this.contract.signer),
maxShare,
0,
])
return this.contract.cook(
[ACTION_REMOVE_COLLATERAL, ACTION_GET_REPAY_SHARE, ACTION_CALL, ACTION_REPAY, ACTION_ADD_COLLATERAL],
[0, 0, 0, 0, 0],
[
// Remove collateral for user to Swapper contract (maxShare)
defaultAbiCoder.encode(["int256", "address"], [maxShare, addr(swapper)]),
// Convert part to amount
defaultAbiCoder.encode(["int256"], [part]),
// Swap collateral less than maxShare to exactly part (converted to amount) asset, deliver asset to user and deliver unused collateral back to user
defaultAbiCoder.encode(["address", "bytes", "bool", "bool", "uint8"], [swapper.address, data.slice(0, -64), true, false, 2]),
// Repay part
defaultAbiCoder.encode(["int256", "address", "bool"], [part, addr(this.contract.signer), false]),
// Add unused collateral back
defaultAbiCoder.encode(["int256", "address", "bool"], [-2, addr(this.contract.signer), false]),
]
)
}
accrue() {
return this.contract.accrue()
}
updateExchangeRate() {
return this.contract.updateExchangeRate()
}
}
Object.defineProperty(KashiPair.prototype, "cmd", {
get: function () {
function proxy(pair, as) {
return new Proxy(pair, {
get: function (target, method) {
return function (...params) {
if (method == "do") {
return {
type: "KashiPairDo",
method: params[0],
params: params.slice(1),
}
}
if (method == "as") {
return proxy(pair, params[0])
}
return {
type: "KashiPairCmd",
pair: target,
method: method,
params: params,
as: as,
}
}
},
})
}
return proxy(this)
},
})
KashiPair.deploy = async function (bentoBox, masterContract, masterContractClass, asset, collateral, oracle, oracleData) {
const initData = defaultAbiCoder.encode(["address", "address", "address", "bytes"], [addr(asset), addr(collateral), addr(oracle), oracleData])
const deployTx = await bentoBox.deploy(masterContract.address, initData, true)
const pair = await masterContractClass.attach((await deployTx.wait()).events[0].args.cloneAddress)
await pair.updateExchangeRate()
const pairHelper = new KashiPair(pair)
pairHelper.initData = initData
await pairHelper.init(bentoBox)
return pairHelper
}
module.exports = {
KashiPair,
}