Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tasks: Support off-chain oracle queries #82

Merged
merged 4 commits into from
Jul 29, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 2 additions & 4 deletions packages/price-oracle/test/PriceOracle.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1551,10 +1551,8 @@ describe('PriceOracle', () => {
})

describe('getPrice (off-chain)', () => {
let base: Contract,
quote: Contract,
feed: Contract,
data = '0x'
let data = '0x'
let base: Contract, quote: Contract, feed: Contract

const OFF_CHAIN_ORACLE_PRICE = fp(5)
const SMART_VAULT_ORACLE_PRICE = fp(10)
Expand Down
31 changes: 30 additions & 1 deletion packages/tasks/contracts/base/BaseTask.sol
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,11 @@ abstract contract BaseTask is IBaseTask, Authorized {
function _getPrice(address base, address quote) internal view virtual returns (uint256) {
address priceOracle = ISmartVault(smartVault).priceOracle();
require(priceOracle != address(0), 'TASK_PRICE_ORACLE_NOT_SET');
return IPriceOracle(priceOracle).getPrice(_wrappedIfNative(base), _wrappedIfNative(quote));
bytes memory extraCallData = _decodeExtraCallData();
return
extraCallData.length == 0
? IPriceOracle(priceOracle).getPrice(_wrappedIfNative(base), _wrappedIfNative(quote))
: IPriceOracle(priceOracle).getPrice(_wrappedIfNative(base), _wrappedIfNative(quote), extraCallData);
}

/**
Expand All @@ -172,4 +176,29 @@ abstract contract BaseTask is IBaseTask, Authorized {
function _wrappedNativeToken() internal view returns (address) {
return ISmartVault(smartVault).wrappedNativeToken();
}

/**
* @dev Decodes any potential extra calldata stored in the calldata space. Tasks relying on the extra calldata
* pattern, assume that the last word of the calldata stores the extra calldata length so it can be decoded. Note
* that tasks relying on this pattern must contemplate this function may return bogus data if no extra calldata
* was given.
*/
function _decodeExtraCallData() private pure returns (bytes memory data) {
uint256 length = uint256(_decodeLastCallDataWord());
if (msg.data.length < length) return new bytes(0);
data = new bytes(length);
assembly {
calldatacopy(add(data, 0x20), sub(sub(calldatasize(), length), 0x20), length)
}
}

/**
* @dev Returns the last calldata word. This function returns zero if the calldata is not long enough.
*/
function _decodeLastCallDataWord() private pure returns (bytes32 result) {
if (msg.data.length < 36) return bytes32(0);
assembly {
result := calldataload(sub(calldatasize(), 0x20))
}
}
}
214 changes: 127 additions & 87 deletions packages/tasks/test/swap/OneInchV5Swapper.test.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,21 @@
import { OP } from '@mimic-fi/v3-authorizer'
import {
assertEvent,
assertIndirectEvent,
BigNumberish,
deploy,
deployFeedMock,
deployProxy,
deployTokenMock,
fp,
getSigners,
MAX_UINT256,
ZERO_ADDRESS,
ZERO_BYTES32,
} from '@mimic-fi/v3-helpers'
import { SignerWithAddress } from '@nomiclabs/hardhat-ethers/dist/src/signer-with-address'
import { expect } from 'chai'
import { Contract } from 'ethers'
import { Contract, ContractTransaction } from 'ethers'
import { defaultAbiCoder } from 'ethers/lib/utils'
import { ethers } from 'hardhat'

import { buildEmptyTaskConfig, deployEnvironment } from '../../src/setup'
import { itBehavesLikeBaseSwapTask } from './BaseSwapTask.behavior'
Expand Down Expand Up @@ -93,7 +95,8 @@ describe('OneInchV5Swapper', () => {

context('when the token in is allowed', () => {
context('when there is a token out set', () => {
let tokenOut: Contract
let tokenOut: Contract,
extraCallData = ''

beforeEach('set default token out', async () => {
tokenOut = await deployTokenMock('TKN')
Expand All @@ -102,113 +105,150 @@ describe('OneInchV5Swapper', () => {
await task.connect(owner).setDefaultTokenOut(tokenOut.address)
})

beforeEach('set price feed', async () => {
const feed = await deployFeedMock(fp(tokenRate), 18)
const setFeedRole = priceOracle.interface.getSighash('setFeed')
await authorizer.connect(owner).authorize(owner.address, priceOracle.address, setFeedRole, [])
await priceOracle.connect(owner).setFeed(tokenIn.address, tokenOut.address, feed.address)
})

beforeEach('set threshold', async () => {
const setDefaultTokenThresholdRole = task.interface.getSighash('setDefaultTokenThreshold')
await authorizer.connect(owner).authorize(owner.address, task.address, setDefaultTokenThresholdRole, [])
await task.connect(owner).setDefaultTokenThreshold(tokenOut.address, thresholdAmount, 0)
})

context('when the smart vault balance passes the threshold', () => {
beforeEach('fund smart vault', async () => {
await tokenIn.mint(smartVault.address, amountIn)
context('when an off-chain oracle is given', () => {
beforeEach('sign off-chain oracle', async () => {
const setSignerRole = priceOracle.interface.getSighash('setSigner')
await authorizer.connect(owner).authorize(owner.address, priceOracle.address, setSignerRole, [])
await priceOracle.connect(owner).setSigner(owner.address, true)

type PriceData = { base: string; quote: string; rate: BigNumberish; deadline: BigNumberish }
const pricesData: PriceData[] = [
{
base: tokenIn.address,
quote: tokenOut.address,
rate: fp(tokenRate),
deadline: MAX_UINT256,
},
{
base: tokenOut.address,
quote: tokenIn.address,
rate: fp(1).mul(fp(1)).div(fp(tokenRate)),
deadline: MAX_UINT256,
},
]

const PricesDataType = 'PriceData(address base, address quote, uint256 rate, uint256 deadline)[]'
const encodedPrices = await defaultAbiCoder.encode([PricesDataType], [pricesData])
const message = ethers.utils.solidityKeccak256(['bytes'], [encodedPrices])
const signature = await owner.signMessage(ethers.utils.arrayify(message))
const data = defaultAbiCoder.encode([PricesDataType, 'bytes'], [pricesData, signature]).slice(2)
const dataLength = defaultAbiCoder.encode(['uint256'], [data.length / 2]).slice(2)
extraCallData = `${data}${dataLength}`
})

context('when the slippage is below the limit', () => {
const data = '0xaabb'
const slippage = fp(0.01)
const expectedAmountOut = amountIn.mul(tokenRate)
const minAmountOut = expectedAmountOut.mul(fp(1).sub(slippage)).div(fp(1))

beforeEach('set max slippage', async () => {
const setDefaultMaxSlippageRole = task.interface.getSighash('setDefaultMaxSlippage')
await authorizer
.connect(owner)
.authorize(owner.address, task.address, setDefaultMaxSlippageRole, [])
await task.connect(owner).setDefaultMaxSlippage(slippage)
})
beforeEach('set threshold', async () => {
const setDefaultTokenThresholdRole = task.interface.getSighash('setDefaultTokenThreshold')
await authorizer
.connect(owner)
.authorize(owner.address, task.address, setDefaultTokenThresholdRole, [])
await task.connect(owner).setDefaultTokenThreshold(tokenOut.address, thresholdAmount, 0)
})

it('executes the expected connector', async () => {
const tx = await task.call(tokenIn.address, amountIn, slippage, data)
const executeTask = async (amountIn, slippage, data): Promise<ContractTransaction> => {
const callTx = await task.populateTransaction.call(tokenIn.address, amountIn, slippage, data)
const callData = `${callTx.data}${extraCallData}`
return owner.sendTransaction({ to: task.address, data: callData })
}

const connectorData = connector.interface.encodeFunctionData('execute', [
tokenIn.address,
tokenOut.address,
amountIn,
minAmountOut,
data,
])
context('when the smart vault balance passes the threshold', () => {
beforeEach('fund smart vault', async () => {
await tokenIn.mint(smartVault.address, amountIn)
})

await assertIndirectEvent(tx, smartVault.interface, 'Executed', {
connector,
data: connectorData,
context('when the slippage is below the limit', () => {
const data = '0xaabb'
const slippage = fp(0.01)
const expectedAmountOut = amountIn.mul(tokenRate)
const minAmountOut = expectedAmountOut.mul(fp(1).sub(slippage)).div(fp(1))

beforeEach('set max slippage', async () => {
const setDefaultMaxSlippageRole = task.interface.getSighash('setDefaultMaxSlippage')
await authorizer
.connect(owner)
.authorize(owner.address, task.address, setDefaultMaxSlippageRole, [])
await task.connect(owner).setDefaultMaxSlippage(slippage)
})

await assertIndirectEvent(tx, connector.interface, 'LogExecute', {
tokenIn,
tokenOut,
amountIn,
minAmountOut,
data,
it('executes the expected connector', async () => {
const tx = await executeTask(amountIn, slippage, data)

const connectorData = connector.interface.encodeFunctionData('execute', [
tokenIn.address,
tokenOut.address,
amountIn,
minAmountOut,
data,
])

await assertIndirectEvent(tx, smartVault.interface, 'Executed', {
connector,
data: connectorData,
})

await assertIndirectEvent(tx, connector.interface, 'LogExecute', {
tokenIn,
tokenOut,
amountIn,
minAmountOut,
data,
})
})
})

it('emits an Executed event', async () => {
const tx = await task.call(tokenIn.address, amountIn, slippage, data)

await assertEvent(tx, 'Executed')
})
it('emits an Executed event', async () => {
const tx = await executeTask(amountIn, slippage, data)

it('updates the balance connectors properly', async () => {
const nextConnectorId = '0x0000000000000000000000000000000000000000000000000000000000000002'
const setBalanceConnectorsRole = task.interface.getSighash('setBalanceConnectors')
await authorizer.connect(owner).authorize(owner.address, task.address, setBalanceConnectorsRole, [])
await task.connect(owner).setBalanceConnectors(ZERO_BYTES32, nextConnectorId)
await assertIndirectEvent(tx, task.interface, 'Executed')
})

const updateBalanceConnectorRole = smartVault.interface.getSighash('updateBalanceConnector')
await authorizer
.connect(owner)
.authorize(task.address, smartVault.address, updateBalanceConnectorRole, [])
it('updates the balance connectors properly', async () => {
const nextConnectorId = '0x0000000000000000000000000000000000000000000000000000000000000002'
const setBalanceConnectorsRole = task.interface.getSighash('setBalanceConnectors')
await authorizer
.connect(owner)
.authorize(owner.address, task.address, setBalanceConnectorsRole, [])
await task.connect(owner).setBalanceConnectors(ZERO_BYTES32, nextConnectorId)

const updateBalanceConnectorRole = smartVault.interface.getSighash('updateBalanceConnector')
await authorizer
.connect(owner)
.authorize(task.address, smartVault.address, updateBalanceConnectorRole, [])

const tx = await executeTask(amountIn, slippage, data)

await assertIndirectEvent(tx, smartVault.interface, 'BalanceConnectorUpdated', {
id: nextConnectorId,
token: tokenOut.address,
amount: minAmountOut,
added: true,
})
})
})

const tx = await task.call(tokenIn.address, amountIn, slippage, data)
context('when the slippage is above the limit', () => {
const slippage = fp(0.01)

await assertIndirectEvent(tx, smartVault.interface, 'BalanceConnectorUpdated', {
id: nextConnectorId,
token: tokenOut.address,
amount: minAmountOut,
added: true,
it('reverts', async () => {
await expect(executeTask(amountIn, slippage, '0x')).to.be.revertedWith('TASK_SLIPPAGE_TOO_HIGH')
})
})
})

context('when the slippage is above the limit', () => {
const slippage = fp(0.01)
context('when the smart vault balance does not pass the threshold', () => {
const amountIn = thresholdAmountInTokenIn.div(2)

beforeEach('fund smart vault', async () => {
await tokenIn.mint(smartVault.address, amountIn)
})

it('reverts', async () => {
await expect(task.call(tokenIn.address, amountIn, slippage, '0x')).to.be.revertedWith(
'TASK_SLIPPAGE_TOO_HIGH'
)
await expect(executeTask(amountIn, 0, '0x')).to.be.revertedWith('TASK_TOKEN_THRESHOLD_NOT_MET')
})
})
})

context('when the smart vault balance does not pass the threshold', () => {
const amountIn = thresholdAmountInTokenIn.div(2)

beforeEach('fund smart vault', async () => {
await tokenIn.mint(smartVault.address, amountIn)
})

context('when no off-chain-oracle is given', () => {
facuspagnuolo marked this conversation as resolved.
Show resolved Hide resolved
it('reverts', async () => {
await expect(task.call(tokenIn.address, amountIn, 0, '0x')).to.be.revertedWith(
'TASK_TOKEN_THRESHOLD_NOT_MET'
)
await expect(task.call(tokenIn.address, amountIn, 0, '0x')).to.be.revertedWith('ORACLE_MISSING_FEED')
})
})
})
Expand Down
Loading