@oldzeppelin/contract 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/.docker/Dockerfile +17 -0
  2. package/.dockerignore +7 -0
  3. package/.env.sample +24 -0
  4. package/.gitlab-ci.yml +51 -0
  5. package/.gitmodules +15 -0
  6. package/.prettierrc +10 -0
  7. package/.solcover.js +4 -0
  8. package/.vscode/settings.json +23 -0
  9. package/LICENSE.MD +51 -0
  10. package/README.md +135 -0
  11. package/contracts/arbitrum/contracts/controllers/UniswapV2ControllerArbitrum.sol +37 -0
  12. package/contracts/arbitrum/contracts/controllers/UniswapV3ControllerArbitrum.sol +46 -0
  13. package/contracts/arbitrum/contracts/oracle/PriceOracleArbitrum.sol +51 -0
  14. package/contracts/main/contracts/controllers/Controller.sol +61 -0
  15. package/contracts/main/contracts/controllers/IController.sol +81 -0
  16. package/contracts/main/contracts/controllers/OneInchV5Controller.sol +332 -0
  17. package/contracts/main/contracts/controllers/UnoswapV2Controller.sol +789 -0
  18. package/contracts/main/contracts/controllers/UnoswapV3Controller.sol +1018 -0
  19. package/contracts/main/contracts/core/CoreWhitelist.sol +192 -0
  20. package/contracts/main/contracts/core/ICoreWhitelist.sol +92 -0
  21. package/contracts/main/contracts/core/IUFarmCore.sol +95 -0
  22. package/contracts/main/contracts/core/UFarmCore.sol +402 -0
  23. package/contracts/main/contracts/fund/FundFactory.sol +59 -0
  24. package/contracts/main/contracts/fund/IUFarmFund.sol +68 -0
  25. package/contracts/main/contracts/fund/UFarmFund.sol +504 -0
  26. package/contracts/main/contracts/oracle/ChainlinkedOracle.sol +71 -0
  27. package/contracts/main/contracts/oracle/IChainlinkAggregator.sol +18 -0
  28. package/contracts/main/contracts/oracle/IPriceOracle.sol +55 -0
  29. package/contracts/main/contracts/oracle/PriceOracle.sol +20 -0
  30. package/contracts/main/contracts/oracle/PriceOracleCore.sol +212 -0
  31. package/contracts/main/contracts/oracle/WstETHOracle.sol +64 -0
  32. package/contracts/main/contracts/permissions/Permissions.sol +54 -0
  33. package/contracts/main/contracts/permissions/UFarmPermissionsModel.sol +136 -0
  34. package/contracts/main/contracts/pool/IPoolAdmin.sol +57 -0
  35. package/contracts/main/contracts/pool/IUFarmPool.sol +304 -0
  36. package/contracts/main/contracts/pool/PerformanceFeeLib.sol +81 -0
  37. package/contracts/main/contracts/pool/PoolAdmin.sol +437 -0
  38. package/contracts/main/contracts/pool/PoolFactory.sol +74 -0
  39. package/contracts/main/contracts/pool/PoolWhitelist.sol +70 -0
  40. package/contracts/main/contracts/pool/UFarmPool.sol +959 -0
  41. package/contracts/main/shared/AssetController.sol +194 -0
  42. package/contracts/main/shared/ECDSARecover.sol +91 -0
  43. package/contracts/main/shared/NZGuard.sol +99 -0
  44. package/contracts/main/shared/SafeOPS.sol +128 -0
  45. package/contracts/main/shared/UFarmCoreLink.sol +83 -0
  46. package/contracts/main/shared/UFarmErrors.sol +16 -0
  47. package/contracts/main/shared/UFarmMathLib.sol +80 -0
  48. package/contracts/main/shared/UFarmOwnableUUPS.sol +59 -0
  49. package/contracts/main/shared/UFarmOwnableUUPSBeacon.sol +34 -0
  50. package/contracts/test/Block.sol +15 -0
  51. package/contracts/test/InchSwapTestProxy.sol +292 -0
  52. package/contracts/test/MockPoolAdmin.sol +8 -0
  53. package/contracts/test/MockUFarmPool.sol +8 -0
  54. package/contracts/test/MockV3wstETHstETHAgg.sol +128 -0
  55. package/contracts/test/MockedWETH9.sol +72 -0
  56. package/contracts/test/OneInchToUFarmTestEnv.sol +466 -0
  57. package/contracts/test/StableCoin.sol +25 -0
  58. package/contracts/test/UFarmMockSequencerUptimeFeed.sol +44 -0
  59. package/contracts/test/UFarmMockV3Aggregator.sol +145 -0
  60. package/contracts/test/UUPSBlock.sol +19 -0
  61. package/contracts/test/ufarmLocal/MulticallV3.sol +220 -0
  62. package/contracts/test/ufarmLocal/controllers/UniswapV2ControllerUFarm.sol +27 -0
  63. package/contracts/test/ufarmLocal/controllers/UniswapV3ControllerUFarm.sol +43 -0
  64. package/deploy/100_test_env_setup.ts +483 -0
  65. package/deploy/20_deploy_uniV2.ts +48 -0
  66. package/deploy/21_create_pairs_uniV2.ts +149 -0
  67. package/deploy/22_deploy_mocked_aggregators.ts +123 -0
  68. package/deploy/22_deploy_wsteth_oracle.ts +65 -0
  69. package/deploy/23_deploy_uniV3.ts +80 -0
  70. package/deploy/24_create_pairs_uniV3.ts +140 -0
  71. package/deploy/25_deploy_oneInch.ts +38 -0
  72. package/deploy/2_deploy_multicall.ts +34 -0
  73. package/deploy/30_deploy_price_oracle.ts +33 -0
  74. package/deploy/3_deploy_lido.ts +114 -0
  75. package/deploy/40_deploy_pool_beacon.ts +19 -0
  76. package/deploy/41_deploy_poolAdmin_beacon.ts +19 -0
  77. package/deploy/42_deploy_ufarmcore.ts +29 -0
  78. package/deploy/43_deploy_fund_beacon.ts +19 -0
  79. package/deploy/4_deploy_tokens.ts +76 -0
  80. package/deploy/50_deploy_poolFactory.ts +35 -0
  81. package/deploy/51_deploy_fundFactory.ts +29 -0
  82. package/deploy/60_init_contracts.ts +101 -0
  83. package/deploy/61_whitelist_tokens.ts +18 -0
  84. package/deploy/70_deploy_uniV2Controller.ts +70 -0
  85. package/deploy/71_deploy_uniV3Controller.ts +67 -0
  86. package/deploy/72_deploy_oneInchController.ts +25 -0
  87. package/deploy/79_whitelist_controllers.ts +125 -0
  88. package/deploy/ufarm/arbitrum/1_prepare_env.ts +82 -0
  89. package/deploy/ufarm/arbitrum/2_deploy_ufarm.ts +178 -0
  90. package/deploy/ufarm/arbitrum-sepolia/1000_prepare_arb_sepolia_env.ts +308 -0
  91. package/deploy-config.json +112 -0
  92. package/deploy-data/oracles.csv +32 -0
  93. package/deploy-data/protocols.csv +10 -0
  94. package/deploy-data/tokens.csv +32 -0
  95. package/docker-compose.yml +67 -0
  96. package/hardhat.config.ts +449 -0
  97. package/index.js +93 -0
  98. package/package.json +82 -0
  99. package/scripts/_deploy_helpers.ts +992 -0
  100. package/scripts/_deploy_network_options.ts +49 -0
  101. package/scripts/activatePool.ts +51 -0
  102. package/scripts/createPool.ts +62 -0
  103. package/scripts/deploy_1inch_proxy.ts +98 -0
  104. package/scripts/pool-data.ts +420 -0
  105. package/scripts/post-deploy.sh +24 -0
  106. package/scripts/setUniV2Rate.ts +252 -0
  107. package/scripts/swapOneInchV5.ts +94 -0
  108. package/scripts/swapUniswapV2.ts +65 -0
  109. package/scripts/swapUniswapV3.ts +71 -0
  110. package/scripts/test.ts +61 -0
  111. package/scripts/typings-copy-artifacts.ts +83 -0
  112. package/tasks/boostPool.ts +39 -0
  113. package/tasks/createFund.ts +44 -0
  114. package/tasks/deboostPool.ts +48 -0
  115. package/tasks/grantUFarmPermissions.ts +57 -0
  116. package/tasks/index.ts +7 -0
  117. package/tasks/mintUSDT.ts +62 -0
  118. package/test/Periphery.test.ts +640 -0
  119. package/test/PriceOracle.test.ts +82 -0
  120. package/test/TestCases.MD +109 -0
  121. package/test/UFarmCore.test.ts +331 -0
  122. package/test/UFarmFund.test.ts +406 -0
  123. package/test/UFarmPool.test.ts +4736 -0
  124. package/test/_fixtures.ts +783 -0
  125. package/test/_helpers.ts +2195 -0
  126. package/test/_oneInchTestData.ts +632 -0
  127. package/tsconfig.json +12 -0
@@ -0,0 +1,24 @@
1
+ #!/bin/bash
2
+
3
+ if [ -z "$1" ]
4
+ then
5
+ echo "Error: no path to the directory for copying artifacts was specified."
6
+ exit 1
7
+ fi
8
+
9
+ OZ_SOURCE_DIR="./.openzeppelin"
10
+ ARTIFACTS_SOURCE_DIR="./artifacts"
11
+ DEPLOYMENTS_SOURCE_DIR="./deployments"
12
+ DEST_PATH="$1"
13
+
14
+ mkdir -p $DEST_PATH
15
+
16
+ # Copy the entire folders into the deployment-artifacts
17
+ cp -r ./.openzeppelin "$DEST_PATH"
18
+ cp -r ./artifacts "$DEST_PATH"
19
+ cp -r ./deployments "$DEST_PATH"
20
+
21
+ # Copy all deployments*.json files from the current directory into the combined_folder
22
+ cp deployments*.json "$DEST_PATH"
23
+
24
+ echo "Folders copied successfully into $DEST_PATH"
@@ -0,0 +1,252 @@
1
+ // SPDX-License-Identifier: UNLICENSED
2
+
3
+ import { ethers } from 'hardhat'
4
+ import * as dotenv from 'dotenv'
5
+ import hre from 'hardhat'
6
+ import fs from 'fs'
7
+ import { MintableToken, setExchangeRate } from '../test/_helpers'
8
+ import { UniswapV2Factory } from '../typechain-types'
9
+ import { BigNumber, BigNumberish } from 'ethers'
10
+ import { customSetTimeout, getInstanceFromDeployment } from './_deploy_helpers'
11
+
12
+ dotenv.config()
13
+
14
+ type ContractInfo = {
15
+ address: string
16
+ abi: any[]
17
+ }
18
+
19
+ type Deployments = {
20
+ name: string
21
+ chainId: string
22
+ contracts: {
23
+ [contractName in RequiredContracts]: ContractInfo
24
+ }
25
+ }
26
+
27
+ const StableCoins = [`USDT`, `USDC`, `DAI`]
28
+ const EthersCoins = [`WETH`, `STETH`, `WSTETH`]
29
+ const IgnoringCoins: string[] = []
30
+ const CommonCoins = [`WBTC`, `MKR`]
31
+ const AllCoins = [...StableCoins, ...EthersCoins, ...IgnoringCoins, ...CommonCoins]
32
+
33
+ type RequiredContracts = (typeof AllCoins)[number] | 'UFarmCore' | 'TestFund' | 'UniswapV2Factory'
34
+
35
+ type Rate = {
36
+ rawName0: (typeof AllCoins)[number]
37
+ rawName1: (typeof AllCoins)[number]
38
+ amount0: BigNumberish
39
+ amount1: BigNumberish
40
+ }
41
+
42
+ async function isUniswapV2PairExist(
43
+ factoryContract: UniswapV2Factory,
44
+ token0Address: string,
45
+ token1Address: string,
46
+ ): Promise<boolean> {
47
+ try {
48
+ const pairAddress = await factoryContract.getPair(token0Address, token1Address)
49
+ return (await hre.ethers.provider.getCode(pairAddress)) !== '0x'
50
+ } catch (error) {
51
+ console.error('Error checking pair existence:', error)
52
+ return false
53
+ }
54
+ }
55
+
56
+ const increaseGasLimit = (estimatedGasLimit: BigNumber) => {
57
+ return estimatedGasLimit.mul(130).div(100) // increase by 30%
58
+ }
59
+
60
+ const interval = 50 * 60 // 50 minutes in seconds
61
+ const day = 24 * 60 * 60 // 24 hours in seconds
62
+
63
+ async function main() {
64
+ async function getCurrentPrice(
65
+ tokenA: MintableToken,
66
+ tokenB: MintableToken,
67
+ factory: UniswapV2Factory,
68
+ ) {
69
+ const pairAddress = await factory.getPair(tokenA.address, tokenB.address)
70
+ const pair = await ethers.getContractAt('UniswapV2Pair', pairAddress, deployer)
71
+ const [reserve0, reserve1] = await pair.getReserves()
72
+ return reserve0
73
+ .mul(10n ** BigInt(await tokenB.decimals()))
74
+ .div(reserve1)
75
+ .mul(997)
76
+ .div(1000)
77
+ }
78
+ function addSinMultiplier(rate: BigNumber, iteration: number): BigNumber {
79
+ let toAdd = rate.mul(interval).div(day).div(10) // 10% of daily rate
80
+ const sinMultiplier = Math.floor(Math.sin(iteration) * 100) + 30
81
+ return rate.add(toAdd.mul(sinMultiplier).div(10))
82
+ }
83
+
84
+ console.log('Starting pool data script...')
85
+ const [deployer] = await ethers.getSigners()
86
+
87
+ const deploymentsConfig: Deployments = JSON.parse(
88
+ fs.readFileSync(hre.deploymentsJsonPath, 'utf8'),
89
+ )
90
+ const deployConfigRates = hre.testnetDeployConfig.initialRates as Rate[]
91
+
92
+ const deployedContracts = deploymentsConfig.contracts
93
+
94
+ const [uniV2factory_instance] = await Promise.all([
95
+ ethers.getContractAt('UniswapV2Factory', deployedContracts.UniswapV2Factory.address, deployer),
96
+ ])
97
+
98
+ for (let iteration = 0; iteration < 15000000; iteration++) {
99
+ // let thisIterationETHUSDprice = BigNumber.from(0)
100
+ // let thisIterationUSDdecimals = 0
101
+
102
+ for (let i = 0; i < deployConfigRates.length; i++) {
103
+ const thisRateConfig = deployConfigRates[i]
104
+ let newRate = BigNumber.from(0)
105
+
106
+ let [amount0, amount1] = [
107
+ BigNumber.from(thisRateConfig.amount0),
108
+ BigNumber.from(thisRateConfig.amount1),
109
+ ]
110
+ const pairName = `${thisRateConfig.rawName0}/${thisRateConfig.rawName1}`
111
+
112
+ let [token0, token1] = [
113
+ await getInstanceFromDeployment<MintableToken>(
114
+ hre,
115
+ deploymentsConfig.contracts[thisRateConfig.rawName0],
116
+ ),
117
+ await getInstanceFromDeployment<MintableToken>(
118
+ hre,
119
+ deploymentsConfig.contracts[thisRateConfig.rawName1],
120
+ ),
121
+ ]
122
+
123
+ if (!token0 || !token1) {
124
+ throw new Error('Unknown token in pair: ' + pairName)
125
+ }
126
+
127
+ const isExist = await isUniswapV2PairExist(
128
+ uniV2factory_instance,
129
+ token0.address,
130
+ token1.address,
131
+ )
132
+ if (!isExist) {
133
+ console.log(`Pair ${pairName} not exist, skipping...`)
134
+ continue
135
+ }
136
+
137
+ const uniV2pool_addr = await uniV2factory_instance.getPair(token0.address, token1.address)
138
+ let [decimals0, decimals1] = [await token0.decimals(), await token1.decimals()]
139
+
140
+ {
141
+ const isStable = {
142
+ a: StableCoins.includes(thisRateConfig.rawName0),
143
+ b: StableCoins.includes(thisRateConfig.rawName1),
144
+ }
145
+
146
+ if (isStable.a && isStable.b) {
147
+ console.log(
148
+ `Ignoring pair ${thisRateConfig.rawName0}/${thisRateConfig.rawName1} because of stable coins`,
149
+ )
150
+ continue
151
+ }
152
+
153
+ const isEthers = {
154
+ a: EthersCoins.includes(thisRateConfig.rawName0),
155
+ b: EthersCoins.includes(thisRateConfig.rawName1),
156
+ }
157
+
158
+ if (isEthers.a && isEthers.b) {
159
+ console.log(
160
+ `Ignoring pair ${thisRateConfig.rawName0}/${thisRateConfig.rawName1} because of ethers coins`,
161
+ )
162
+ continue
163
+ }
164
+
165
+ if ((isEthers.a && isStable.b) || (isEthers.b && isStable.a)) {
166
+ const stableA_etherB = isEthers.a && isStable.b
167
+ }
168
+
169
+ const isCommon = {
170
+ a: CommonCoins.includes(thisRateConfig.rawName0),
171
+ b: CommonCoins.includes(thisRateConfig.rawName1),
172
+ }
173
+
174
+ const isIgnoring = {
175
+ a: IgnoringCoins.includes(thisRateConfig.rawName0),
176
+ b: IgnoringCoins.includes(thisRateConfig.rawName1),
177
+ }
178
+
179
+ if (isIgnoring.a || isIgnoring.b) {
180
+ console.log(
181
+ `Ignoring pair ${thisRateConfig.rawName0}/${
182
+ thisRateConfig.rawName1
183
+ } because of ignoring coin (${
184
+ isIgnoring.a ? thisRateConfig.rawName0 : thisRateConfig.rawName1
185
+ })`,
186
+ )
187
+ continue
188
+ }
189
+ }
190
+
191
+ console.log(`\n\nRate: ${JSON.stringify(thisRateConfig)}`)
192
+
193
+ const uniV2pool_instance = await ethers.getContractAt(
194
+ 'UniswapV2Pair',
195
+ uniV2pool_addr,
196
+ deployer,
197
+ )
198
+
199
+ const pairToken0 = await uniV2pool_instance.token0()
200
+ const isReveresed = pairToken0 === token1.address
201
+
202
+ let [reserve0, reserve1] = await uniV2pool_instance.getReserves()
203
+ if (isReveresed) {
204
+ ;[reserve0, reserve1] = [reserve1, reserve0]
205
+ }
206
+
207
+ let originalRate = amount1.mul(10n ** BigInt(decimals0)).div(amount0)
208
+ let actualRate = reserve1.mul(10n ** BigInt(decimals0)).div(reserve0)
209
+ let reversedRate = reserve0.mul(10n ** BigInt(decimals1)).div(reserve1)
210
+
211
+ console.log(
212
+ `Original rate: ${originalRate.toString()}\nActual rate: ${actualRate.toString()}\nReversed actual rate: ${reversedRate.toString()}`,
213
+ )
214
+
215
+ if (newRate.isZero()) {
216
+ newRate = addSinMultiplier(actualRate, iteration)
217
+ }
218
+ let newRateRevesed = BigNumber.from(10n ** BigInt(decimals0 + decimals1) / newRate.toBigInt())
219
+
220
+ console.log(`New rate: ${newRate.toString()}, reversed: ${newRateRevesed}`)
221
+
222
+ await customSetTimeout(3)
223
+
224
+ console.log(
225
+ `token0: ${token0.address}\ntoken1: ${
226
+ token1.address
227
+ }\nnewRate: ${newRate.toString()}\ndeployer: ${deployer.address}\nuniV2factory_instance: ${
228
+ uniV2factory_instance.address
229
+ }`,
230
+ )
231
+
232
+ await setExchangeRate(token0, token1, newRateRevesed, deployer, uniV2factory_instance)
233
+ await customSetTimeout(3)
234
+
235
+ const rateAfterChanging = await getCurrentPrice(token0, token1, uniV2factory_instance)
236
+
237
+ console.log(`Rate after changing: ${rateAfterChanging.toString()}\n`)
238
+ }
239
+
240
+ console.log(`Iteration ${iteration} finished!\n\n\n`)
241
+ await customSetTimeout(1) // 50 minutes
242
+ }
243
+
244
+ console.log('Pool data script done!')
245
+
246
+ process.exit(0)
247
+ }
248
+
249
+ main().catch((error) => {
250
+ console.error(error)
251
+ process.exitCode = 1
252
+ })
@@ -0,0 +1,94 @@
1
+ // SPDX-License-Identifier: UNLICENSED
2
+
3
+ import hre from 'hardhat'
4
+ import { BigNumber } from 'ethers'
5
+ import { UFarmPool, StableCoin } from '../typechain-types'
6
+ import {
7
+ ISwapResponse,
8
+ constants,
9
+ encodePoolOneInchSwap,
10
+ oneInchCustomUnoswapTo,
11
+ } from '../test/_helpers'
12
+ import { oneinchETHConstants } from '../test/_oneInchTestData'
13
+
14
+ async function main() {
15
+ const {
16
+ pool,
17
+ tokenin,
18
+ tokenout,
19
+ amountin,
20
+ amountoutmin,
21
+ deadline,
22
+ oneInchAddr,
23
+ uniswapV2Router,
24
+ uniswapV2Factory,
25
+ } = {
26
+ pool: '0x7f9B0a701882Dc9c904517533e27772905275112',
27
+ tokenin: '0xd71fe004d84b10FbD161838F87A94f2327A315a1',
28
+ tokenout: '0xeF8DF16e4BAe9582393Fd96099ed670526F09a8D',
29
+ amountin: '1000000',
30
+ amountoutmin: '1',
31
+ deadline: Math.floor(Date.now() / 100 + 100).toString(),
32
+ oneInchAddr: '0x001C073d1ed78a0aADc31f2D320300aE30D1a085', // Double check this address
33
+ uniswapV2Router: '0xA37Fc726C2acc26a5807F32a40f7D2Fe7540F4cb',
34
+ uniswapV2Factory: '0x2a973622751ce6Ae37b3567c328a78BC3A59A050',
35
+ }
36
+ console.log(deadline)
37
+
38
+ const Pool = (await hre.ethers.getContractAt('UFarmPool', pool)) as UFarmPool
39
+
40
+ const [tokenInstanceIn, tokenInstanceOut] = [
41
+ (await hre.ethers.getContractAt('StableCoin', tokenin)) as StableCoin,
42
+ (await hre.ethers.getContractAt('StableCoin', tokenout)) as StableCoin,
43
+ ]
44
+
45
+ const [balanceInBefore, balanceOutBefore] = await Promise.all([
46
+ tokenInstanceIn.balanceOf(Pool.address),
47
+ tokenInstanceOut.balanceOf(Pool.address),
48
+ ])
49
+
50
+ console.log(`Swapping ${amountin} ${tokenin} for at least ${amountoutmin} ${tokenout} on ${pool}`)
51
+
52
+ const OneInchResponse = oneinchETHConstants.swap.usdt100_weth.response
53
+
54
+ const injectedOneInchResponse = await oneInchCustomUnoswapTo(
55
+ // OneInchResponse.request as ISwapRequest,
56
+ OneInchResponse as ISwapResponse,
57
+ oneInchAddr,
58
+ amountin,
59
+ Pool.address,
60
+ [tokenInstanceIn.address, tokenInstanceOut.address],
61
+ uniswapV2Router,
62
+ uniswapV2Factory,
63
+ )
64
+
65
+ const oneInchSwapTxData = encodePoolOneInchSwap(injectedOneInchResponse.tx.data)
66
+
67
+ const tx = await Pool.protocolAction(
68
+ constants.UFarm.prtocols.OneInchProtocolString,
69
+ oneInchSwapTxData,
70
+ )
71
+ const receipt = await tx.wait()
72
+
73
+ const [balanceInAfter, balanceOutAfter] = await Promise.all([
74
+ tokenInstanceIn.balanceOf(Pool.address),
75
+ tokenInstanceOut.balanceOf(Pool.address),
76
+ ])
77
+
78
+ console.log(
79
+ `Swapped with tx hash: ${receipt.transactionHash}\nSpent ${balanceInBefore.sub(
80
+ balanceInAfter,
81
+ )} ${await tokenInstanceIn.symbol()} and received ${balanceOutAfter.sub(
82
+ balanceOutBefore,
83
+ )} ${await tokenInstanceOut.symbol()}`,
84
+ )
85
+
86
+ console.log('Swap operation complete.')
87
+ }
88
+
89
+ main()
90
+ .then(() => process.exit(0))
91
+ .catch((error) => {
92
+ console.error(error)
93
+ process.exit(1)
94
+ })
@@ -0,0 +1,65 @@
1
+ // SPDX-License-Identifier: UNLICENSED
2
+
3
+ import hre from 'hardhat'
4
+ import { BigNumber } from 'ethers'
5
+ import { UFarmPool, StableCoin } from '../typechain-types'
6
+ import { constants, encodePoolSwapDataUniswapV2 } from '../test/_helpers'
7
+
8
+ async function main() {
9
+ const { pool, tokenin, tokenout, amountin, amountoutmin, deadline } = {
10
+ pool: '0x7f9B0a701882Dc9c904517533e27772905275112',
11
+ tokenin: '0xd71fe004d84b10FbD161838F87A94f2327A315a1',
12
+ tokenout: '0xeF8DF16e4BAe9582393Fd96099ed670526F09a8D',
13
+ amountin: '1000000',
14
+ amountoutmin: '1',
15
+ deadline: Math.floor(Date.now() / 100 + 100).toString(),
16
+ }
17
+ console.log(deadline)
18
+
19
+ const [amountInB, amountOutMinB] = [BigNumber.from(amountin), BigNumber.from(amountoutmin)]
20
+
21
+ const Pool = (await hre.ethers.getContractAt('UFarmPool', pool)) as UFarmPool
22
+
23
+ const [tokenInstanceIn, tokenInstanceOut] = [
24
+ (await hre.ethers.getContractAt('StableCoin', tokenin)) as StableCoin,
25
+ (await hre.ethers.getContractAt('StableCoin', tokenout)) as StableCoin,
26
+ ]
27
+
28
+ const [balanceInBefore, balanceOutBefore] = await Promise.all([
29
+ tokenInstanceIn.balanceOf(Pool.address),
30
+ tokenInstanceOut.balanceOf(Pool.address),
31
+ ])
32
+
33
+ console.log(`Swapping ${amountin} ${tokenin} for at least ${amountoutmin} ${tokenout} on ${pool}`)
34
+
35
+ const tx = await Pool.protocolAction(
36
+ constants.UFarm.prtocols.UniswapV2ProtocolString,
37
+ encodePoolSwapDataUniswapV2(amountInB, amountOutMinB, deadline, [
38
+ tokenInstanceIn.address,
39
+ tokenInstanceOut.address,
40
+ ]),
41
+ )
42
+ const receipt = await tx.wait()
43
+
44
+ const [balanceInAfter, balanceOutAfter] = await Promise.all([
45
+ tokenInstanceIn.balanceOf(Pool.address),
46
+ tokenInstanceOut.balanceOf(Pool.address),
47
+ ])
48
+
49
+ console.log(
50
+ `Swapped with tx hash: ${receipt.transactionHash}\nSpent ${balanceInBefore.sub(
51
+ balanceInAfter,
52
+ )} ${await tokenInstanceIn.symbol()} and received ${balanceOutAfter.sub(
53
+ balanceOutBefore,
54
+ )} ${await tokenInstanceOut.symbol()}`,
55
+ )
56
+
57
+ console.log('Swap operation complete.')
58
+ }
59
+
60
+ main()
61
+ .then(() => process.exit(0))
62
+ .catch((error) => {
63
+ console.error(error)
64
+ process.exit(1)
65
+ })
@@ -0,0 +1,71 @@
1
+ // SPDX-License-Identifier: UNLICENSED
2
+
3
+ import hre from 'hardhat'
4
+ import { BigNumber } from 'ethers'
5
+ import { UFarmPool, StableCoin } from '../typechain-types'
6
+ import { constants, encodePoolSwapUniV3SingleHopExactInput } from '../test/_helpers'
7
+
8
+ async function main() {
9
+ const { pool, tokenin, tokenout, amountin, amountoutmin, deadline } = {
10
+ pool: '0x7f9B0a701882Dc9c904517533e27772905275112',
11
+ tokenin: '0xd71fe004d84b10FbD161838F87A94f2327A315a1',
12
+ tokenout: '0xeF8DF16e4BAe9582393Fd96099ed670526F09a8D',
13
+ amountin: '1000000',
14
+ amountoutmin: '1',
15
+ deadline: Math.floor(Date.now() / 100 + 100).toString(),
16
+ }
17
+ console.log(deadline)
18
+
19
+ const [amountInB, amountOutMinB] = [BigNumber.from(amountin), BigNumber.from(amountoutmin)]
20
+
21
+ const Pool = (await hre.ethers.getContractAt('UFarmPool', pool)) as UFarmPool
22
+
23
+ const [tokenInstanceIn, tokenInstanceOut] = [
24
+ (await hre.ethers.getContractAt('StableCoin', tokenin)) as StableCoin,
25
+ (await hre.ethers.getContractAt('StableCoin', tokenout)) as StableCoin,
26
+ ]
27
+
28
+ const [balanceInBefore, balanceOutBefore] = await Promise.all([
29
+ tokenInstanceIn.balanceOf(Pool.address),
30
+ tokenInstanceOut.balanceOf(Pool.address),
31
+ ])
32
+
33
+ console.log(`Swapping ${amountin} ${tokenin} for at least ${amountoutmin} ${tokenout} on ${pool}`)
34
+
35
+ const tx = await Pool.protocolAction(
36
+ constants.UFarm.prtocols.UniswapV3ProtocolString,
37
+ encodePoolSwapUniV3SingleHopExactInput(
38
+ tokenInstanceIn.address,
39
+ tokenInstanceOut.address,
40
+ 3000,
41
+ Pool.address,
42
+ deadline,
43
+ amountInB,
44
+ amountOutMinB,
45
+ constants.UniV3.MIN_SQRT_RATIO
46
+ )
47
+ )
48
+ const receipt = await tx.wait()
49
+
50
+ const [balanceInAfter, balanceOutAfter] = await Promise.all([
51
+ tokenInstanceIn.balanceOf(Pool.address),
52
+ tokenInstanceOut.balanceOf(Pool.address),
53
+ ])
54
+
55
+ console.log(
56
+ `Swapped with tx hash: ${receipt.transactionHash}\nSpent ${balanceInBefore.sub(
57
+ balanceInAfter,
58
+ )} ${await tokenInstanceIn.symbol()} and received ${balanceOutAfter.sub(
59
+ balanceOutBefore,
60
+ )} ${await tokenInstanceOut.symbol()}`,
61
+ )
62
+
63
+ console.log('Swap operation complete.')
64
+ }
65
+
66
+ main()
67
+ .then(() => process.exit(0))
68
+ .catch((error) => {
69
+ console.error(error)
70
+ process.exit(1)
71
+ })
@@ -0,0 +1,61 @@
1
+ // SPDX-License-Identifier: UNLICENSED
2
+
3
+ import { ethers } from 'hardhat'
4
+ import hre from 'hardhat'
5
+ import {
6
+ MintableToken,
7
+ _prepareInvite,
8
+ _signWithdrawRequest,
9
+ bitsToBigNumber,
10
+ constants,
11
+ encodePoolAddLiqudityDataAsIsUniswapV2,
12
+ encodePoolAddLiqudityDataUniswapV2,
13
+ encodePoolSwapDataUniswapV2,
14
+ get1InchResult,
15
+ getBlockchainTimestamp,
16
+ getEventFromTx,
17
+ mintAndCreatePairUniV2,
18
+ mintAndDeposit,
19
+ prepareWithdrawRequest,
20
+ } from '../test/_helpers'
21
+ import {
22
+ IERC20,
23
+ IERC20Metadata,
24
+ PoolAdmin,
25
+ PriceOracle,
26
+ StableCoin,
27
+ UFarmCore,
28
+ UFarmFund,
29
+ UFarmPool,
30
+ UniswapV2Factory,
31
+ UniswapV2Factory__factory,
32
+ UniswapV2Pair,
33
+ UniswapV2Pair__factory,
34
+ UniswapV2Router02,
35
+ UnoswapV2Controller,
36
+ } from '../typechain-types'
37
+
38
+ import { BigNumber, BigNumberish, Contract } from 'ethers'
39
+ import { customSetTimeout, getInstanceFromDeployment, retryOperation } from './_deploy_helpers'
40
+ import { SignerWithAddress } from '@nomiclabs/hardhat-ethers/signers'
41
+
42
+ async function main() {
43
+ console.log('Starting')
44
+ const { deployer, fundOwner } = await hre.getNamedAccounts()
45
+
46
+ const USDCaddr = '0xaf88d065e77c8cC2239327C5EDb3A432268e5831'
47
+ const USDTaddr = '0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9'
48
+ const DOLAaddr = '0x6a7661795c374c0bfc635934efaddff3a7ee23b6'
49
+
50
+ const response = await get1InchResult(USDTaddr, DOLAaddr, BigNumber.from(10).pow(6))
51
+
52
+ console.log(`1inch response: ${JSON.stringify(response, null, 2)}`)
53
+
54
+ console.log('END OF SCRIPT')
55
+ process.exit(0)
56
+ }
57
+
58
+ main().catch((error) => {
59
+ console.error(error)
60
+ process.exitCode = 1
61
+ })
@@ -0,0 +1,83 @@
1
+ // SPDX-License-Identifier: UNLICENSED
2
+
3
+ import fs from 'fs'
4
+ import path from 'path'
5
+
6
+ const sourceDirectories = [
7
+ './artifacts/contracts/main/contracts',
8
+ './artifacts/contracts/test/UniswapV3/@uniswap/v3-core/contracts/UniswapV3Pool.sol',
9
+ './artifacts/contracts/test/UniswapV3/@uniswap/v3-periphery/contracts/SwapRouter.sol',
10
+ './artifacts/contracts/test/UniswapV3/@uniswap/v3-periphery/contracts/NonfungiblePositionManager.sol',
11
+ './artifacts/contracts/test/UniswapV3/@uniswap/v3-periphery/contracts/lens/QuoterV2.sol',
12
+ './artifacts/contracts/test/UniswapV3/@uniswap/v3-core/contracts/UniswapV3Factory.sol',
13
+ ]
14
+ const targetDirectory = './ufarm-evm-typings/build/artifacts'
15
+
16
+ // Ensure target directory exists or create it
17
+ if (!fs.existsSync(targetDirectory)) {
18
+ fs.mkdirSync(targetDirectory, { recursive: true })
19
+ }
20
+
21
+ // Read all subdirectories inside the source directory
22
+ for (const sourceDirectory of sourceDirectories) {
23
+ if (!fs.existsSync(sourceDirectory)) {
24
+ console.warn(`Skipping source directory ${sourceDirectory}`)
25
+ continue
26
+ }
27
+
28
+ const solDirs = getAllSolFolders(sourceDirectory)
29
+
30
+ solDirs.forEach((contractDir) => {
31
+ const contractName = contractDir.split('.sol')[0].split('/').pop()
32
+
33
+ if (contractName) {
34
+ const rootContractDir = contractDir.split('.sol')[0].slice(0, -contractName.length)
35
+
36
+ const sourceFile = path.join(contractDir, contractName + '.json')
37
+
38
+ const isInterface = contractName[0] == 'I' && contractName[1] == contractName[1].toUpperCase()
39
+ if (isInterface) {
40
+ const nonInterfaceSourceDir = path.join(
41
+ rootContractDir,
42
+ contractName.slice(1) + '.sol',
43
+ )
44
+
45
+ if (fs.existsSync(nonInterfaceSourceDir) && solDirs.includes(nonInterfaceSourceDir)) {
46
+ console.log(`Skipping interface of ${contractName} in favor of ${nonInterfaceSourceDir}`)
47
+ return
48
+ }
49
+ }
50
+
51
+ // Skip if file doesn't exist
52
+ if (!fs.existsSync(sourceFile)) {
53
+ console.warn(`Skipping ${sourceFile}`)
54
+ return
55
+ }
56
+ const targetFile = path.join(targetDirectory, '/', contractName + '.json')
57
+ console.log(`Copying ${sourceFile} to ${targetFile}`)
58
+ fs.copyFileSync(sourceFile, targetFile)
59
+ }
60
+ })
61
+ }
62
+ function getAllSolFolders(dir: string, solFolders: string[] = []): string[] {
63
+ if (dir.endsWith('.sol')) {
64
+ solFolders.push(dir)
65
+ }
66
+ const files = fs.readdirSync(dir)
67
+
68
+ for (const file of files) {
69
+ const filePath = path.join(dir, file)
70
+ const stat = fs.statSync(filePath)
71
+
72
+ if (stat.isDirectory()) {
73
+ getAllSolFolders(filePath, solFolders)
74
+ } else if (file.endsWith('.sol')) {
75
+ const folder = path.dirname(filePath)
76
+ if (!solFolders.includes(folder)) {
77
+ solFolders.push(folder)
78
+ }
79
+ }
80
+ }
81
+
82
+ return solFolders
83
+ }
@@ -0,0 +1,39 @@
1
+ // SPDX-License-Identifier: UNLICENSED
2
+
3
+ import { task } from 'hardhat/config'
4
+ import { types } from 'hardhat/config'
5
+
6
+ task('boostPool', 'Increases exchange rate of pool in testnet')
7
+ .addParam('pool', 'address of the pool', '0xPool', types.string)
8
+ .setAction(async function (taskArgs, hre) {
9
+ if (!hre.ethers.utils.isAddress(taskArgs.pool)) {
10
+ if ((taskArgs.pool as string) === '0xPool') {
11
+ console.log(
12
+ `Default manager address was not set, manager will be a caller with address: ${taskArgs.pool}`,
13
+ )
14
+ } else {
15
+ throw new Error(`Manager (${taskArgs.pool}) is not a proper EVM address.`)
16
+ }
17
+ }
18
+ const [signer] = await hre.ethers.getSigners()
19
+ console.log(
20
+ `Signer addr:\n${await signer.getAddress()}\n`,
21
+ `Signer balance:\n${await signer.getBalance()}\n`,
22
+ )
23
+
24
+ const pool_instance = await hre.ethers.getContractAt('UFarmPool', taskArgs.pool)
25
+ const valueToken = await pool_instance.valueToken()
26
+ const token_instance = await hre.ethers.getContractAt('StableCoin', valueToken)
27
+
28
+ console.log(`Increasing pool rate(${pool_instance.address})`)
29
+
30
+ const initialTotalCost = await pool_instance.getTotalCost()
31
+ const initialRate = await pool_instance.getExchangeRate()
32
+
33
+ const ONE_HUNDRED_BUCKS = hre.ethers.utils.parseUnits('100', 6)
34
+ const depositAmount = initialTotalCost.gt(ONE_HUNDRED_BUCKS) ? initialTotalCost.div(5) : ONE_HUNDRED_BUCKS
35
+ await (await token_instance.mint(pool_instance.address, depositAmount)).wait()
36
+ const rateAfterDeposit = await pool_instance.getExchangeRate()
37
+
38
+ console.log(`Initial rate: ${initialRate} | Rate after deposit: ${rateAfterDeposit}`)
39
+ })