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

Paul/swap rune #305

Merged
merged 8 commits into from
Nov 21, 2023
Merged
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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# edge-exchange-plugins

## 1.1.0 (2023-11-20)

- added: RUNE support for Thorchain swaps

## 1.0.4 (2023-11-09)

- changed: Block Polygon USDC/USDC.e trading and fix codes, where necessary
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "edge-exchange-plugins",
"version": "1.0.4",
"version": "1.1.0",
"description": "Exchange-rate sources for the Edge core",
"homepage": "https://edge.app/",
"repository": {
Expand Down Expand Up @@ -65,7 +65,7 @@
"chai": "^4.2.0",
"cleaner-config": "^0.1.10",
"crypto-browserify": "^3.12.0",
"edge-core-js": "^1.4.0",
"edge-core-js": "^1.11.0",
"edge-currency-accountbased": "^2.9.0",
"edge-currency-plugins": "^2.4.1",
"esbuild-loader": "^2.20.0",
Expand Down
146 changes: 113 additions & 33 deletions src/swap/defi/thorchain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,14 @@ import {
EdgeCurrencyWallet,
EdgeFetchFunction,
EdgeFetchOptions,
EdgeMemo,
EdgeSpendInfo,
EdgeSwapInfo,
EdgeSwapPlugin,
EdgeSwapQuote,
EdgeSwapRequest,
EdgeTransaction,
EdgeTxSwap,
SwapBelowLimitError,
SwapCurrencyError
} from 'edge-core-js/types'
Expand All @@ -39,7 +41,7 @@ import {
promiseWithTimeout,
QueryParams
} from '../../util/utils'
import { EdgeSwapRequestPlugin } from '../types'
import { EdgeSwapRequestPlugin, MakeTxParams } from '../types'
import { getEvmApprovalData, getEvmTokenData } from './defiUtils'

const pluginId = 'thorchain'
Expand Down Expand Up @@ -151,7 +153,7 @@ export const MAINNET_CODE_TRANSCRIPTION: { [cc: string]: ChainTypes } = {
dogecoin: 'DOGE',
ethereum: 'ETH',
litecoin: 'LTC',
thorchain: 'THOR'
thorchainrune: 'THOR'
}

export const asInitOptions = asObject({
Expand Down Expand Up @@ -179,11 +181,11 @@ export const asInboundAddresses = asArray(

export const asPool = asObject({
asset: asString,
status: asString,
// status: asString,
assetPrice: asString,
assetPriceUSD: asString,
assetDepth: asString,
runeDepth: asString
assetPriceUSD: asString
// assetDepth: asString,
// runeDepth: asString
})

export const asAssetSpread = asObject({
Expand Down Expand Up @@ -230,7 +232,7 @@ const asQuoteSwap = asObject({
// asset: asString, // "ETH.WBTC-0X2260FAC5E5542A773AA44FBCFEDF7C193BC2C599",
// outbound: asString // "22117"
// }),
inbound_address: asString, // "0x88e8def37dc9d2acd67f1c1574ad09ca49827374",
inbound_address: asOptional(asString), // "0x88e8def37dc9d2acd67f1c1574ad09ca49827374",
// max_streaming_quantity: asNumber, // 18,
memo: asString, // "=:ETH.WBTC-0X2260FAC5E5542A773AA44FBCFEDF7C193BC2C599:0x04c5998ded94f89263370444ce64a99b7dbc9f46:0/10/0",
// outbound_delay_blocks: asNumber, // 114,
Expand Down Expand Up @@ -279,7 +281,7 @@ interface CalcSwapResponse {
maxFulfillmentSeconds?: number
toNativeAmount: string
toExchangeAmount: string
thorAddress: string
thorAddress?: string
router?: string
memo: string
}
Expand Down Expand Up @@ -446,13 +448,12 @@ export function makeThorchainPlugin(
const poolJson = await poolResponse.json()
const pools = asPools(poolJson)

const sourcePool = pools.find(pool => {
const [asset] = pool.asset.split('-')
return asset === `${fromMainnetCode}.${fromCurrencyCode}`
})
if (sourcePool == null) {
throw new SwapCurrencyError(swapInfo, request)
}
const sourcePool = getPool(
request,
fromMainnetCode,
fromCurrencyCode,
pools
)
const [
sourceAsset,
sourceTokenContractAddressAllCaps
Expand All @@ -463,13 +464,7 @@ export function makeThorchainPlugin(
: undefined
log(`sourceAsset: ${sourceAsset}`)

const destPool = pools.find(pool => {
const [asset] = pool.asset.split('-')
return asset === `${toMainnetCode}.${toCurrencyCode}`
})
if (destPool == null) {
throw new SwapCurrencyError(swapInfo, request)
}
const destPool = getPool(request, toMainnetCode, toCurrencyCode, pools)

let calcResponse: CalcSwapResponse
if (quoteFor === 'from') {
Expand Down Expand Up @@ -532,7 +527,20 @@ export function makeThorchainPlugin(
let ethNativeAmount = fromNativeAmount
let publicAddress = thorAddress
let approvalData
let memoType: EdgeMemo['type']

const swapData: EdgeTxSwap = {
orderUri: 'https://track.ninerealms.com/',
isEstimate,
payoutAddress: toAddress,
payoutCurrencyCode: toCurrencyCode,
payoutNativeAmount: toNativeAmount,
payoutWalletId: toWallet.id,
plugin: { ...swapInfo }
}

if (EVM_CURRENCY_CODES[fromMainnetCode]) {
memoType = 'hex'
if (fromMainnetCode !== fromCurrencyCode) {
if (router == null)
throw new Error(`Missing router address for ${fromMainnetCode}`)
Expand All @@ -541,13 +549,17 @@ export function makeThorchainPlugin(
`Missing sourceTokenContractAddress for ${fromMainnetCode}`
)
// Need to use ethers.js to craft a proper tx that calls Thorchain contract, then extract the data payload
if (thorAddress == null) {
throw new Error('Invalid vault address')
}
memo = await getEvmTokenData({
assetAddress: sourceTokenContractAddress,
amountToSwapWei: Number(fromNativeAmount),
contractAddress: router,
vaultAddress: thorAddress,
memo
})
memo = memo.replace('0x', '')

// Token transactions send no ETH (or other EVM mainnet coin)
ethNativeAmount = '0'
Expand All @@ -560,9 +572,35 @@ export function makeThorchainPlugin(
nativeAmount: fromNativeAmount
})
} else {
memo = '0x' + Buffer.from(memo).toString('hex')
memo = Buffer.from(memo).toString('hex')
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nitpick: Replace buffer.from toString pattern with base16 from rfc4648

}
} else if (fromWallet.currencyInfo.pluginId === 'thorchainrune') {
const makeTxParams: MakeTxParams = {
type: 'MakeTxDeposit',
assets: [
{
amount: fromNativeAmount,
asset: 'THOR.RUNE',
decimals: THOR_LIMIT_UNITS
}
],
memo,
metadata: {},
swapData
}

return {
addTxidToOrderUri: true,
canBePartial,
maxFulfillmentSeconds,
request,
makeTxParams,
swapInfo,
fromNativeAmount,
expirationDate: new Date(Date.now() + EXPIRATION_MS)
}
} else {
memoType = 'text'
// Cannot yet do tokens on non-EVM chains
if (fromMainnetCode !== fromCurrencyCode) {
throw new SwapCurrencyError(swapInfo, request)
Expand All @@ -571,11 +609,18 @@ export function makeThorchainPlugin(

let preTx: EdgeTransaction | undefined
if (approvalData != null) {
approvalData = approvalData.replace('0x', '')
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nitpick: do this where it's defined


const spendInfo: EdgeSpendInfo = {
currencyCode: request.fromCurrencyCode,
memos: [
{
type: memoType,
value: approvalData
}
],
spendTargets: [
{
memo: approvalData,
nativeAmount: '0',
publicAddress: sourceTokenContractAddress
}
Expand All @@ -588,24 +633,26 @@ export function makeThorchainPlugin(
preTx = await request.fromWallet.makeSpend(spendInfo)
}

if (publicAddress == null) {
throw new Error('Invalid publicAddress')
}

const spendInfo: EdgeSpendInfo = {
currencyCode: request.fromCurrencyCode,
memos: [
{
type: memoType,
value: memo
}
],
spendTargets: [
{
memo,
nativeAmount: ethNativeAmount,
publicAddress
}
],

swapData: {
isEstimate,
payoutAddress: toAddress,
payoutCurrencyCode: toCurrencyCode,
payoutNativeAmount: toNativeAmount,
payoutWalletId: toWallet.id,
plugin: { ...swapInfo }
},
swapData,
otherParams: {
outputSort: 'targets'
}
Expand All @@ -626,6 +673,7 @@ export function makeThorchainPlugin(
}

return {
addTxidToOrderUri: true,
canBePartial,
maxFulfillmentSeconds,
request,
Expand Down Expand Up @@ -655,6 +703,38 @@ export function makeThorchainPlugin(
return out
}

const getPool = (
request: EdgeSwapRequestPlugin,
mainnetCode: string,
tokenCode: string,
pools: Pool[]
): Pool => {
if (mainnetCode === 'THOR' && tokenCode === 'RUNE') {
// Create a fake pool for rune. Use BTC pool to find rune USD price
const btcPool = pools.find(pool => pool.asset === 'BTC.BTC')

if (btcPool == null) {
throw new SwapCurrencyError(swapInfo, request)
}
const { assetPrice, assetPriceUSD } = btcPool
const pool: Pool = {
asset: 'THOR.RUNE',
assetPrice: '1',
assetPriceUSD: div(assetPriceUSD, assetPrice, 16)
}
return pool
}

const pool = pools.find(pool => {
const [asset] = pool.asset.split('-')
return asset === `${mainnetCode}.${tokenCode}`
})
if (pool == null) {
throw new SwapCurrencyError(swapInfo, request)
}
return pool
}

const calcSwapFrom = async ({
log,
fetch,
Expand Down
20 changes: 0 additions & 20 deletions src/swap/defi/xrp/xrpDexTypes.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,5 @@
import { EdgeMetadata, EdgeTxSwap } from 'edge-core-js'
import { Client, Wallet } from 'xrpl'

/**
* Duplicated from edge-currency-accountbased until this
* is elevatd to a type in edge-core-js
*/
export interface MakeTxParams {
type: 'MakeTxDexSwap'
metadata?: EdgeMetadata
swapData?: EdgeTxSwap
fromTokenId?: string
fromNativeAmount: string
toTokenId?: string
toNativeAmount: string

/**
* UNIX time (seconds) to expire the DEX swap if it hasn't executed
*/
expiration?: number
}

/**
* Below types copied from https://github.com/florent-uzio/xrpl.js-demo.git
*/
Expand Down
3 changes: 1 addition & 2 deletions src/swap/defi/xrpDex.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,8 @@ import {
promiseWithTimeout,
shuffleArray
} from '../../util/utils'
import { EdgeSwapRequestPlugin } from '../types'
import { EdgeSwapRequestPlugin, MakeTxParams } from '../types'
import { getBuyQuote, getSellQuote } from './xrp/xrpDexHelpers'
import { MakeTxParams } from './xrp/xrpDexTypes'

const pluginId = 'xrpdex'
const swapInfo: EdgeSwapInfo = {
Expand Down
33 changes: 32 additions & 1 deletion src/swap/types.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { asEither, asNumber, asString } from 'cleaners'
import { EdgeCurrencyWallet } from 'edge-core-js'
import { EdgeCurrencyWallet, EdgeMetadata, EdgeTxSwap } from 'edge-core-js'

export interface EdgeSwapRequestPlugin {
fromWallet: EdgeCurrencyWallet
Expand All @@ -20,3 +20,34 @@ export const asNumberString = (raw: any): string => {
export interface StringMap {
[key: string]: string
}

/**
* Duplicated from edge-currency-accountbased until this
* is elevatd to a type in edge-core-js
*/
export type MakeTxParams =
| {
type: 'MakeTxDexSwap'
metadata?: EdgeMetadata
swapData?: EdgeTxSwap
fromTokenId?: string
fromNativeAmount: string
toTokenId?: string
toNativeAmount: string

/**
* UNIX time (seconds) to expire the DEX swap if it hasn't executed
*/
expiration?: number
}
| {
type: 'MakeTxDeposit'
assets: Array<{
amount: string
asset: string
decimals: string
}>
memo: string
metadata?: EdgeMetadata
swapData?: EdgeTxSwap
}
Loading