增加流动性
任何人都可以通过调用函数 addLiquidity 向池中添加流动性。有
首次增加流动性:可以存入任意数量的 BSV 和 Token 。
添加更多流动性: BSV 和 Token 存入的比率必须与池中的现有比率相匹配(第 22 行)。
// add bsv and token to liquidity pool
public function addLiquidity(PubKey sender, Sig senderSig, int tokenAmount, int senderBalance, int senderKeyIndex, int oldTokenBalance,
int lpSenderBalance, int lpSenderKeyIndex, int newBsvBalance, SigHashPreimage txPreimage) {
require(checkSig(senderSig, sender));
int oldBsvBalance = SigHash.value(txPreimage);
// mint new lp tokens for the liquidity provider
if (oldBsvBalance == 0) {
// initialize pool
// initially, just mint new lp tokens per the amount of new bsvs deposited
int lpMint = newBsvBalance;
require(this.lpToken.mint(sender, lpSenderBalance, lpMint, lpSenderKeyIndex));
} else {
// add more liquidity
int bsvAmount = newBsvBalance - oldBsvBalance;
// deposit ratio must be the same with current pool ration
// i.e., oldBsvBalance / oldTokenBalance == bsvAmount / tokenAmount
require(oldBsvBalance * tokenAmount == bsvAmount * oldTokenBalance);
// mint new lp tokens, proportinal to the amount of new bsvs deposited
int lpMint = this.lpToken.totalSupply() * bsvAmount / oldBsvBalance;
require(this.lpToken.mint(sender, lpSenderBalance, lpMint, lpSenderKeyIndex));
}
// transfer tokens to the pool
require(this.token.transferFrom(sender, this.poolPubkey, tokenAmount, senderBalance, senderKeyIndex, oldTokenBalance, senderKeyIndex));
require(this.propagateState(newBsvBalance, txPreimage));
}