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

eng-360: add openMarkets feature - save wip #119

Closed
wants to merge 10 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
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
5 changes: 5 additions & 0 deletions .changeset/serious-peas-explain.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@mangrovedao/mgv": patch
---

Added open markets
3 changes: 2 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
{
"typescript.tsdk": "node_modules/typescript/lib"
"typescript.tsdk": "node_modules/typescript/lib",
"editor.defaultFormatter": "biomejs.biome"
}
2 changes: 1 addition & 1 deletion biome.json
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@
"javascript": {
"formatter": {
"quoteStyle": "single",
"trailingCommas": "all",
"trailingComma": "all",
"semicolons": "asNeeded"
}
},
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"clean": "rimraf src/_esm src/_cjs src/_types",
"format": "biome format . --write",
"lint": "biome check .",
"lint:fix": "bun run lint --write",
"lint:fix": "biome check . -apply",
"prepublishOnly": "bun scripts/prepublishOnly.ts",
"test": "vitest -c ./test/vitest.config.ts dev",
"test:ci": "CI=true vitest -c ./test/vitest.config.ts --retry=3"
Expand Down
30 changes: 30 additions & 0 deletions src/actions/open-markets.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { describe, expect, inject, it } from 'vitest'
import { getClient } from '~test/src/client.js'
import { getOpenMarkets } from './open-markets.js'

const params = inject('mangrove')

describe('Getting the open markets', () => {
it('should get the open markets', async () => {
const client = getClient()
const openMarkets = await getOpenMarkets(client, params)

console.log(openMarkets.markets, 'markets')

expect(openMarkets.markets[0]?.tkn0).toBeTypeOf('object')
expect(openMarkets.markets[0]?.tkn1).toBeTypeOf('object')
expect(openMarkets.markets[0]?.tickSpacing).toBeTypeOf('bigint')

expect(openMarkets.markets[1]?.tkn0).toBeTypeOf('object')
expect(openMarkets.markets[1]?.tkn1).toBeTypeOf('object')
expect(openMarkets.markets[1]?.tickSpacing).toBeTypeOf('bigint')
})

it('should get the open markets config', async () => {
const client = getClient()
const openMarkets = await getOpenMarkets(client, params)
console.log(openMarkets.marketsConfig, 'config')

expect(openMarkets.marketsConfig).toBeTypeOf('object')
})
})
40 changes: 40 additions & 0 deletions src/actions/open-markets.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// import type { SimulationParams } from '~mgv/types/actions/simulation.js'
// import type { openMarketsABI } from '../builder/open-markets.js'
import type { Client } from 'viem'
import { multicall } from 'viem/actions'

import type { OpenMarketsResult } from '~mgv/types/actions/open-markets.js'
import type { MangroveActionsDefaultParams } from '~mgv/types/index.js'
import {
openMarketsParams,
parseOpenMarketResult,
} from '../builder/open-markets.js'
import { getAction } from '../utils/getAction.js'

export async function getOpenMarkets(
client: Client,
actionParams: MangroveActionsDefaultParams,
): Promise<OpenMarketsResult> {
const { mgvReader } = actionParams

const result = await getAction(
client,
multicall,
'multicall',
)({
contracts: [
{
address: mgvReader,
...openMarketsParams(),
},
],
allowFailure: false,
})

const parsedOpenMarkets = await parseOpenMarketResult({
client,
result: result[0],
})

return parsedOpenMarkets
}
138 changes: 138 additions & 0 deletions src/builder/open-markets.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
import {
type ContractFunctionParameters,
type ContractFunctionReturnType,
parseAbi,
} from 'viem'
import type { Abi, Client } from 'viem'

import { multicall } from 'viem/actions'
import type { Token } from '~mgv/_types/index.js'
import { buildToken } from '~mgv/addresses/index.js'
import type { OpenMarketsResult } from '~mgv/types/actions/open-markets.js'
import type { LocalConfig } from '~mgv/types/lib.js'
import { getAction } from '~mgv/utils/getAction.js'

export const openMarketsABI = parseAbi([
'struct Market { address tkn0; address tkn1; uint tickSpacing; }',
'struct LocalUnpacked { bool active; uint fee; uint rawDensity; uint binPosInLeaf; uint level3; uint level2; uint level1; uint root; uint kilo_offer_gasbase; bool lock; uint last;}',
'struct MarketConfig { LocalUnpacked config01; LocalUnpacked config10; }',
'function openMarkets() external view returns (Market[] memory, MarketConfig[] memory)',
])

/**
*
* @param params market order params
* @returns the parameters for a market order by tick for viem
* @example
*
* ```ts
* walletClient.writeContract({
* address: '0x...',
* ...marketOrderParams({
* ...
* })
* });
* ```
*
*/
export function openMarketsParams() {
return {
abi: openMarketsABI,
functionName: 'openMarkets',
args: [],
} satisfies Omit<
ContractFunctionParameters<typeof openMarketsABI, 'view', 'openMarkets'>,
'address'
>
}

export type ParseOpenMarketsParams = {
client: Client
result: ContractFunctionReturnType<
typeof openMarketsABI,
'view',
'openMarkets'
>
}

/**
*
* @param result the result of open markets
* @returns the parsed open markets result
*/
export async function parseOpenMarketResult({
client,
result,
}: ParseOpenMarketsParams): Promise<OpenMarketsResult> {
const [rawMarkets, rawMarketsConfigs] = result

const markets = await Promise.all(
rawMarkets.map(async ({ tkn0, tkn1, tickSpacing }) => {
const tokenAbi = [
{
name: 'decimals',
inputs: [],
outputs: [{ type: 'uint8' }],
stateMutability: 'view',
type: 'function',
},
{
name: 'symbol',
inputs: [],
outputs: [{ type: 'string' }],
stateMutability: 'view',
type: 'function',
},
]

const tokenInfos = await getAction(
client,
multicall,
'multicall',
)({
contracts: [tkn0, tkn1].flatMap((address) => [
{ functionName: 'decimals', abi: tokenAbi as Abi, address },
{ functionName: 'symbol', abi: tokenAbi as Abi, address },
]),
allowFailure: false,
})

const buildTokenFromInfo = (address: string, index: number) => {
const decimalsIndex = index * 2
const symbolIndex = decimalsIndex + 1
return buildToken({
address: address as `0x${string}`,
symbol: tokenInfos[symbolIndex] as string,
displayDecimals: tokenInfos[decimalsIndex] as number,
priceDisplayDecimals: tokenInfos[decimalsIndex] as number,
mgvTestToken: false,
}) as Token
}

return {
tkn0: buildTokenFromInfo(tkn0, 0),
tkn1: buildTokenFromInfo(tkn1, 1),
tickSpacing,
}
}),
)

const marketsConfig = rawMarketsConfigs?.map((item) => {
const { config01, config10 } = item

return {
config01: {
...config01,
density: Number(config01.rawDensity),
offer_gasbase: config01.kilo_offer_gasbase,
} as LocalConfig,
config10: {
...config10,
density: Number(config10.rawDensity),
offer_gasbase: config10.kilo_offer_gasbase,
} as LocalConfig,
}
})

return { markets, marketsConfig }
}
10 changes: 10 additions & 0 deletions src/types/actions/open-markets.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import type { LocalConfig, Token } from '~mgv/_types/index.js'

export type OpenMarketsResult = {
markets: {
tkn0: Token
tkn1: Token
tickSpacing: bigint
}[]
marketsConfig: { config01: LocalConfig; config10: LocalConfig }[]
}