Skip to content

Instantly share code, notes, and snippets.

@itoonx
Last active May 10, 2021 15:18
Show Gist options
  • Save itoonx/43d5fe2d69640a035f95b8d8703816e2 to your computer and use it in GitHub Desktop.
Save itoonx/43d5fe2d69640a035f95b8d8703816e2 to your computer and use it in GitHub Desktop.
Example Swap -> AMM Model of Uniswap
/**
Example Swap -> AMM Model of Uniswap V1,V2
**/
// Testing online
// https://jsfiddle.net/itoonx/xqah6e9v/
const asset = 'BNB'
const quote = 'XRP'
const LiquidityPool = {
BNB: 10,
XRP: 500,
}
console.log('Init Liquidity Pool', LiquidityPool)
function addLiquidity (token, tAmount) {
LiquidityPool[token] += tAmount
return LiquidityPool[token]
}
function takeLiquidity (token, tAmount) {
if (tAmount >= LiquidityPool[token]) {
LiquidityPool[token] -= tAmount
return LiquidityPool[token]
} else {
return new Error('No Liquidity')
}
}
function swapAndLiquify (tokenA, tokenB, tAmount) {
try {
console.log('LiquidityPool[tokenA]', LiquidityPool[tokenA])
console.log('LiquidityPool[tokenB]', LiquidityPool[tokenB])
let kWeight = LiquidityPool[tokenA] * LiquidityPool[tokenB]
console.log('kWeight', kWeight)
addLiquidity(tokenA, tAmount) // add 10 BNB to Pool
console.log('LiquidityPool[tokenA]', LiquidityPool[tokenA])
console.log('LiquidityPool[tokenB]', LiquidityPool[tokenB])
const allocP = kWeight / LiquidityPool[tokenA]
const tReceive = LiquidityPool[tokenB] - allocP
console.log('tReceive', tReceive, tokenB)
/* const pRate = tReceive / tAmount
console.log('pRate', pRate) */
takeLiquidity(tokenB, tReceive)
return tReceive
} catch (error) {
return new Error('Error', error)
}
}
let trades1 = swapAndLiquify('BNB', 'XRP', 1)
console.log('SWAP', trades1)
/* let trades2 = swapAndLiquify('BNB', 'XRP', 100)
console.log('SWAP', trades2)
let trades3 = swapAndLiquify('XRP', 'BNB', 50)
console.log('SWAP', trades3) */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment