Skip to content

Commit

Permalink
add ashswap aggregator swaps
Browse files Browse the repository at this point in the history
  • Loading branch information
michavie committed Jun 10, 2024
1 parent ada5359 commit 78c294d
Show file tree
Hide file tree
Showing 6 changed files with 195 additions and 28 deletions.
85 changes: 66 additions & 19 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

22 changes: 14 additions & 8 deletions src/extensions/ashswap/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,19 +1,25 @@
import React from 'react'
import { SwapTab } from './swap/SwapTab'
import { useApp } from '../../../shared/hooks/useApp'
import { AppSection } from '../../../shared/ui/elements'
import { TabButton } from '../../../shared/ui/elements'
import { faSyncAlt } from '@fortawesome/free-solid-svg-icons'
import { TabGroup, TabList, TabPanel, TabPanels } from '@headlessui/react'

export const App = () => {
const app = useApp()

// The app hook provides access to the extension configuration
// and useful methods for interacting with DAOs.
console.log(app)

return (
<div>
<AppSection title="Example Section">
<p>Example paragraph</p>
</AppSection>
</div>
<TabGroup>
<TabList className="flex items-center space-x-2 md:space-x-4 mb-4">
<TabButton icon={faSyncAlt}>General</TabButton>
</TabList>
<TabPanels>
<TabPanel>
<SwapTab />
</TabPanel>
</TabPanels>
</TabGroup>
)
}
7 changes: 7 additions & 0 deletions src/extensions/ashswap/src/helpers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { Network } from '../../../shared/types'
import { ChainId } from '@ashswap/ash-sdk-js/out'

export const getAshswapChainId = (network: Network): ChainId.Devnet | ChainId.Mainnet => {
if (network === 'devnet') return ChainId.Devnet
return ChainId.Mainnet
}
99 changes: 99 additions & 0 deletions src/extensions/ashswap/src/swap/SwapTab.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import { AshswapToken } from '../types'
import { getAshswapChainId } from '../helpers'
import { Aggregator } from '@ashswap/ash-sdk-js/out'
import { useApp } from '../../../../shared/hooks/useApp'
import { AppSection } from '../../../../shared/ui/elements'
import { Address, TokenTransfer } from '@multiversx/sdk-core/out'
import { Button, EntityTransferSelector, Select } from '@peerme/web-ui'
import { Constants, ProposalAction, createAction } from '@peerme/core-ts'
import React, { SyntheticEvent, useEffect, useMemo, useState } from 'react'

const DefaultSlippage = 100 // 1% = 1_000

export function SwapTab() {
const app = useApp()
const aggregator = useMemo(
() => new Aggregator({ chainId: getAshswapChainId(app.config.network) }),
[app.config.network]
)
const [payment, setPayment] = useState<TokenTransfer | null>(null)
const [availableTokens, setAvailableTokens] = useState<AshswapToken[]>([])
const availableTokensSorted = useMemo(
() => availableTokens.sort((a, b) => a.id.localeCompare(b.id)),
[availableTokens]
)
const [seletedToken, setSelectedToken] = useState<string | null>(Constants.EgldTokenIdentifier)
const [computedAction, setComputedAction] = useState<ProposalAction | null>(null)

useEffect(() => {
aggregator.getTokens().then((tokens) => setAvailableTokens(tokens))
}, [])

useEffect(() => {
if (!payment) return
computeSwap()
}, [payment?.tokenIdentifier, payment?.amountAsBigInteger.toString()])

const computeSwap = async () => {
if (!payment || !seletedToken) return
const { getInteraction, sorResponse } = await aggregator.aggregate(
payment.tokenIdentifier,
seletedToken,
payment.amountAsBigInteger.toNumber(),
DefaultSlippage
)
const tx = await getInteraction(async (warning) => {
console.log('aggregator swap warning', warning)
return true
}).catch(() => null)
console.log('aggregator response', sorResponse, tx)
if (!tx) return
tx.withSender(new Address(app.config.entity.address)).buildTransaction()
const contract = tx.getContractAddress().bech32()
if (!contract) return
const tokenTransfers = payment.isEgld() ? [] : [payment]
setComputedAction(
createAction(contract, tx.getFunction().toString(), tx.getValue().toString(), tx.getArguments() as any, tokenTransfers)
)
}

const handleSubmit = (e: SyntheticEvent) => {
e.preventDefault()
if (!seletedToken) {
app.showToast('Please select a target token', 'error')
return
}
if (seletedToken === payment?.tokenIdentifier) {
app.showToast('Source and target token must be different', 'error')
return
}
if (!computedAction) return
app.requestDirectProposalAction(computedAction)
}

return (
<AppSection title="Swap">
<form onSubmit={handleSubmit}>
<EntityTransferSelector
config={app.config.walletConfig}
entity={app.config.entity}
permissions={[]}
onSelected={setPayment}
skipTokenTypes={['nft']}
className="mb-8"
/>
<Select id="targetToken" onChange={setSelectedToken} className="mb-4">
<option value={Constants.EgldTokenIdentifier}>{Constants.EgldTokenIdentifier}</option>
{availableTokensSorted.map((token) => (
<option key={token.id} value={token.id}>
{token.id.split('-')[0]} ({token.id})
</option>
))}
</Select>
<Button color="blue" className="block w-full" type="submit">
Add Swap Action
</Button>
</form>
</AppSection>
)
}
5 changes: 5 additions & 0 deletions src/extensions/ashswap/src/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export type AshswapToken = {
id: string
decimal?: number
coingeckoId?: string
}
5 changes: 4 additions & 1 deletion src/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@
"preversion": "npm run lint && npm run build"
},
"peerDependencies": {
"dayjs": "^1.11.10",
"@apollo/client": ">=3.7.7",
"@elrondnetwork/transaction-decoder": ">=1.0.0",
"@fortawesome/fontawesome-svg-core": ">=6.1.1",
Expand All @@ -49,6 +48,7 @@
"axios": "^1.3.4",
"clsx": "^2.0.0",
"collect.js": "^4.36.1",
"dayjs": "^1.11.10",
"next": ">=13.0.0",
"pluralize": "^8.0.0",
"react": ">=18.2.0",
Expand Down Expand Up @@ -87,5 +87,8 @@
"rollup-plugin-terser": "^7.0.2",
"rollup-plugin-typescript2": "^0.36.0",
"typescript": "^5.4.5"
},
"dependencies": {
"@ashswap/ash-sdk-js": "^2.0.11"
}
}

0 comments on commit 78c294d

Please sign in to comment.