质押挖矿合约的奖励算法实现(python)
class Distribution:
'''
每个人的收益为:质押量*单位质押每秒可获得的累积收益 - 已经提取的收益
添加流动性的时候:【已经提取的收益】的值增加(相当于【增加后的质押量*单位质押的每秒可获得的累积收益】多算了,所以最后要剪去)
移除流动性的时候:【已经提取的收益】的值减少(相当于【减少后的质押量*单位质押的每秒可获得的累积收益】少算了,所以最后要加上)
'''
toke_num = 0 #每秒分配的token数量
start_time = 0 #开始时间
supply = 0 #总代币供应量
acc_income = 0 #单位质押的每秒可获得的累积收益
addr_staking = {} #每个地址质押代币数量
addr_withdraw = {} #每个地址已提取的代币数量
def __init__(self, init_toke_num):
self.toke_num = init_toke_num
self.start_time = time.time()
def get_time_interval(self):
return int(time.time() - self.start_time)
def add_liquality(self, addr, token):
if addr not in self.addr_staking:
self.addr_staking[addr] = 0
self.addr_withdraw[addr] = 0
if self.supply!=0:
self.acc_income += self.get_time_interval()*self.toke_num/self.supply
self.supply+=token
self.addr_staking[addr] += token
self.addr_withdraw[addr] = self.addr_staking[addr]*self.acc_income
def remove_liquality(self, addr, token):
if addr not in self.addr_staking:
print('地址不存在')
return;
# 避免提取的token数量大于质押的token数量
token = min(token, self.addr_staking[addr])
self.addr_staking[addr] -= token
self.addr_withdraw[addr] -= self.addr_staking[addr]*self.acc_income
self.supply-=token
self.acc_income = self.toke_num/self.supply
def withdraw_token(self, addr, token):
if addr not in self.addr_staking:
print('地址不存在')
return;
# 避免提取的token数量大于质押的token数量
token = min(token, self.addr_staking[addr]*self.acc_income - self.addr_withdraw[addr])
self.addr_withdraw[addr] += token
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!