Rewrite base unittest module, reinstate more contract methods

This commit is contained in:
lash 2023-02-09 06:49:18 +00:00
parent ffc041c1a3
commit ae2c1b4124
Signed by: lash
GPG Key ID: 21D2E7BB88C2A746
6 changed files with 351 additions and 226 deletions

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1 +1 @@
from .base import * from .newbase import *

View File

@ -0,0 +1,134 @@
# standard imports
import logging
import os
# external imports
from chainlib.eth.unittest.ethtester import EthTesterCase
from chainlib.eth.tx import (
receipt,
)
from chainlib.eth.block import (
block_latest,
block_by_number,
)
from chainlib.eth.nonce import RPCNonceOracle
from chainlib.eth.constant import ZERO_ADDRESS
# local imports
from erc20_demurrage_token import (
DemurrageTokenSettings,
DemurrageToken,
)
logg = logging.getLogger()
#BLOCKTIME = 5 # seconds
TAX_LEVEL = int(10000 * 2) # 2%
# calc "1-(0.98)^(1/518400)" <- 518400 = 30 days of blocks
# 0.00000003897127107225
#PERIOD = int(60/BLOCKTIME) * 60 * 24 * 30 # month
PERIOD = 10
class TestTokenDeploy:
"""tax level is ppm, 1000000 = 100%"""
def __init__(self, rpc, token_symbol='FOO', token_name='Foo Token', sink_address=ZERO_ADDRESS, supply=10**12, tax_level=TAX_LEVEL, period=PERIOD):
self.tax_level = tax_level
self.period_seconds = period * 60
self.settings = DemurrageTokenSettings()
self.settings.name = token_name
self.settings.symbol = token_symbol
self.settings.decimals = 6
self.settings.demurrage_level = tax_level ** (1 / period)
self.settings.period_minutes = period
self.settings.sink_address = sink_address
self.sink_address = self.settings.sink_address
logg.debug('using demurrage token settings: {}'.format(self.settings))
o = block_latest()
self.start_block = rpc.do(o)
o = block_by_number(self.start_block, include_tx=False)
r = rpc.do(o)
try:
self.start_time = int(r['timestamp'], 16)
except TypeError:
self.start_time = int(r['timestamp'])
self.default_supply = supply
#self.default_supply_cap = int(self.default_supply * 10)
self.default_supply_cap = 0
def deploy(self, rpc, deployer_address, interface, mode, supply_cap=0):
tx_hash = None
o = None
(tx_hash, o) = interface.constructor(deployer_address, self.settings, redistribute=False, cap=0)
r = rpc.do(o)
o = receipt(tx_hash)
r = rpc.do(o)
assert r['status'] == 1
self.start_block = r['block_number']
self.address = r['contract_address']
o = block_by_number(r['block_number'])
r = rpc.do(o)
self.start_time = r['timestamp']
return self.address
class TestDemurrage(EthTesterCase):
def setUp(self):
super(TestDemurrage, self).setUp()
period = PERIOD
try:
period = getattr(self, 'period')
except AttributeError as e:
pass
self.deployer = TestTokenDeploy(self.rpc, period=period)
self.default_supply = self.deployer.default_supply
self.default_supply_cap = self.deployer.default_supply_cap
self.start_block = None
self.address = None
self.start_time = None
def deploy(self, interface):
self.address = self.deployer.deploy(self.rpc, self.accounts[0], interface, mode, supply_cap=self.default_supply_cap)
self.start_block = self.deployer.start_block
self.start_time = self.deployer.start_time
self.tax_level = self.deployer.tax_level
self.period_seconds = self.deployer.period_seconds
self.sink_address = self.deployer.sink_address
logg.debug('contract address {} start block {} start time {}'.format(self.address, self.start_block, self.start_time))
def assert_within_lower(self, v, target, tolerance_ppm):
lower_target = target - (target * (tolerance_ppm / 1000000))
self.assertGreaterEqual(v, lower_target)
self.assertLessEqual(v, target)
logg.debug('asserted within lower {} <= {} <= {}'.format(lower_target, v, target))
def tearDown(self):
pass
class TestDemurrageDefault(TestDemurrage):
def setUp(self):
super(TestDemurrageDefault, self).setUp()
nonce_oracle = RPCNonceOracle(self.accounts[0], self.rpc)
c = DemurrageToken(self.chain_spec, signer=self.signer, nonce_oracle=nonce_oracle)
self.deploy(c)
logg.info('deployed with mode {}'.format(self.mode))

View File

@ -1,3 +1,3 @@
chainlib-eth>=0.1.0,<0.2.0 chainlib-eth~=0.4.11
eth-erc20~=0.3.0 eth-erc20~=0.5.0
funga-eth~=0.6.0 funga-eth~=0.6.0

View File

@ -138,96 +138,97 @@ contract DemurrageTokenSingleCap {
} }
// // Change sink address for redistribution // Change sink address for redistribution
// function setSinkAddress(address _sinkAddress) public { function setSinkAddress(address _sinkAddress) public {
// require(msg.sender == owner); require(msg.sender == owner);
// sinkAddress = _sinkAddress; sinkAddress = _sinkAddress;
// } }
//
// // Given address will be allowed to call the mintTo() function // Given address will be allowed to call the mintTo() function
// function addMinter(address _minter) public returns (bool) { function addMinter(address _minter) public returns (bool) {
// require(msg.sender == owner); require(msg.sender == owner);
// minter[_minter] = true; minter[_minter] = true;
// return true; return true;
// } }
//
// // Given address will no longer be allowed to call the mintTo() function // Given address will no longer be allowed to call the mintTo() function
// function removeMinter(address _minter) public returns (bool) { function removeMinter(address _minter) public returns (bool) {
// require(msg.sender == owner || _minter == msg.sender); require(msg.sender == owner || _minter == msg.sender);
// minter[_minter] = false; minter[_minter] = false;
// return true; return true;
// } }
//
// /// Implements ERC20 /// Implements ERC20
// function balanceOf(address _account) public view returns (uint256) { function balanceOf(address _account) public view returns (uint256) {
// uint256 baseBalance; int128 baseBalance;
// uint256 currentDemurragedAmount; int128 currentDemurragedAmount;
// uint256 periodCount; uint256 periodCount;
//
// baseBalance = baseBalanceOf(_account); baseBalance = ABDKMath64x64.fromUInt(baseBalanceOf(_account));
//
// periodCount = getMinutesDelta(demurrageTimestamp); periodCount = getMinutesDelta(demurrageTimestamp);
//
// currentDemurragedAmount = uint128(decayBy(demurrageAmount * 10000000000, periodCount)); currentDemurragedAmount = ABDKMath64x64.mul(baseBalance, demurrageAmount);
// return decayBy(ABDKMath64x64.toUInt(currentDemurragedAmount), periodCount);
// return (baseBalance * currentDemurragedAmount) / (nanoDivider * 1000000000000);
// } //return (baseBalance * currentDemurragedAmount) / (nanoDivider * 1000000000000);
// }
// /// Balance unmodified by demurrage
// function baseBalanceOf(address _account) public view returns (uint256) { // Balance unmodified by demurrage
// return account[_account]; function baseBalanceOf(address _account) public view returns (uint256) {
// } return account[_account];
// }
// /// Increases base balance for a single account
// function increaseBaseBalance(address _account, uint256 _delta) private returns (bool) { /// Increases base balance for a single account
// uint256 oldBalance; function increaseBaseBalance(address _account, uint256 _delta) private returns (bool) {
// uint256 newBalance; uint256 oldBalance;
// uint256 workAccount; uint256 newBalance;
// uint256 workAccount;
// workAccount = uint256(account[_account]);
// workAccount = uint256(account[_account]);
// if (_delta == 0) {
// return false; if (_delta == 0) {
// } return false;
// }
// oldBalance = baseBalanceOf(_account);
// account[_account] = oldBalance + _delta; oldBalance = baseBalanceOf(_account);
// return true; account[_account] = oldBalance + _delta;
// } return true;
// }
// /// Decreases base balance for a single account
// function decreaseBaseBalance(address _account, uint256 _delta) private returns (bool) { /// Decreases base balance for a single account
// uint256 oldBalance; function decreaseBaseBalance(address _account, uint256 _delta) private returns (bool) {
// uint256 newBalance; uint256 oldBalance;
// uint256 workAccount; uint256 newBalance;
// uint256 workAccount;
// workAccount = uint256(account[_account]);
// workAccount = uint256(account[_account]);
// if (_delta == 0) {
// return false; if (_delta == 0) {
// } return false;
// }
// oldBalance = baseBalanceOf(_account);
// require(oldBalance >= _delta, 'ERR_OVERSPEND'); // overspend guard oldBalance = baseBalanceOf(_account);
// account[_account] = oldBalance - _delta; require(oldBalance >= _delta, 'ERR_OVERSPEND'); // overspend guard
// return true; account[_account] = oldBalance - _delta;
// } return true;
// }
// // Creates new tokens out of thin air, and allocates them to the given address
// // Triggers tax // Creates new tokens out of thin air, and allocates them to the given address
// function mintTo(address _beneficiary, uint256 _amount) external returns (bool) { // Triggers tax
// uint256 baseAmount; function mintTo(address _beneficiary, uint256 _amount) external returns (bool) {
// uint256 baseAmount;
// require(minter[msg.sender], 'ERR_ACCESS');
// require(minter[msg.sender], 'ERR_ACCESS');
// changePeriod();
// baseAmount = toBaseAmount(_amount); //changePeriod();
// supply += _amount; baseAmount = toBaseAmount(_amount);
// increaseBaseBalance(_beneficiary, baseAmount); supply += _amount;
// emit Mint(msg.sender, _beneficiary, _amount); increaseBaseBalance(_beneficiary, baseAmount);
// saveRedistributionSupply(); emit Mint(msg.sender, _beneficiary, _amount);
// return true; saveRedistributionSupply();
// } return true;
}
// Deserializes the redistribution word // Deserializes the redistribution word
function toRedistribution(uint256 _participants, uint256 _demurrageModifierPpm, uint256 _value, uint256 _period) public pure returns(redistributionItem memory) { function toRedistribution(uint256 _participants, uint256 _demurrageModifierPpm, uint256 _value, uint256 _period) public pure returns(redistributionItem memory) {
@ -239,46 +240,46 @@ contract DemurrageTokenSingleCap {
return redistribution; return redistribution;
} }
//
// // Serializes the demurrage period part of the redistribution word // Serializes the demurrage period part of the redistribution word
// function toRedistributionPeriod(redistributionItem memory _redistribution) public pure returns (uint256) { function toRedistributionPeriod(redistributionItem memory _redistribution) public pure returns (uint256) {
// return uint256(_redistribution.period); return uint256(_redistribution.period);
// } }
//
// // Serializes the supply part of the redistribution word // Serializes the supply part of the redistribution word
// function toRedistributionSupply(redistributionItem memory _redistribution) public pure returns (uint256) { function toRedistributionSupply(redistributionItem memory _redistribution) public pure returns (uint256) {
// return uint256(_redistribution.value); return uint256(_redistribution.value);
// } }
//
// // Serializes the number of participants part of the redistribution word // Serializes the number of participants part of the redistribution word
// function toRedistributionDemurrageModifier(redistributionItem memory _redistribution) public pure returns (uint256) { function toRedistributionDemurrageModifier(redistributionItem memory _redistribution) public pure returns (uint256) {
// return uint256(_redistribution.demurrage); return uint256(_redistribution.demurrage);
// } }
//
//
// // Client accessor to the redistributions array length // Client accessor to the redistributions array length
// function redistributionCount() public view returns (uint256) { function redistributionCount() public view returns (uint256) {
// return redistributions.length; return redistributions.length;
// } }
//
// // Save the current total supply amount to the current redistribution period // Save the current total supply amount to the current redistribution period
// function saveRedistributionSupply() private returns (bool) { function saveRedistributionSupply() private returns (bool) {
// redistributionItem memory currentRedistribution; redistributionItem memory currentRedistribution;
// uint256 grownSupply; uint256 grownSupply;
//
// grownSupply = totalSupply(); grownSupply = totalSupply();
// currentRedistribution = redistributions[redistributions.length-1]; currentRedistribution = redistributions[redistributions.length-1];
// currentRedistribution.value = uint72(grownSupply); currentRedistribution.value = uint72(grownSupply);
//
// redistributions[redistributions.length-1] = currentRedistribution; redistributions[redistributions.length-1] = currentRedistribution;
// return true; return true;
// } }
//
// // Get the demurrage period of the current block number // Get the demurrage period of the current block number
// function actualPeriod() public view returns (uint128) { function actualPeriod() public view returns (uint128) {
// return uint128((block.timestamp - periodStart) / periodDuration + 1); return uint128((block.timestamp - periodStart) / periodDuration + 1);
// } }
//
// // Retrieve next redistribution if the period threshold has been crossed // // Retrieve next redistribution if the period threshold has been crossed
// function checkPeriod() private view returns (redistributionItem memory) { // function checkPeriod() private view returns (redistributionItem memory) {
// redistributionItem memory lastRedistribution; // redistributionItem memory lastRedistribution;
@ -292,14 +293,14 @@ contract DemurrageTokenSingleCap {
// } // }
// return lastRedistribution; // return lastRedistribution;
// } // }
//
// function getDistribution(uint256 _supply, uint256 _demurrageAmount) public view returns (uint256) { // function getDistribution(uint256 _supply, uint256 _demurrageAmount) public view returns (uint256) {
// uint256 difference; // uint256 difference;
// //
// difference = _supply * (resolutionFactor - (_demurrageAmount * 10000000000)); // difference = _supply * (resolutionFactor - (_demurrageAmount * 10000000000));
// return difference / resolutionFactor; // return difference / resolutionFactor;
// } // }
//
// function getDistributionFromRedistribution(redistributionItem memory _redistribution) public returns (uint256) { // function getDistributionFromRedistribution(redistributionItem memory _redistribution) public returns (uint256) {
// uint256 redistributionSupply; // uint256 redistributionSupply;
// uint256 redistributionDemurrage; // uint256 redistributionDemurrage;
@ -321,12 +322,12 @@ contract DemurrageTokenSingleCap {
// totalSink += baseUnit; // totalSink += baseUnit;
// return unit; // return unit;
// } // }
//
// // Calculate the time delta in whole minutes passed between given timestamp and current timestamp // Calculate the time delta in whole minutes passed between given timestamp and current timestamp
// function getMinutesDelta(uint256 _lastTimestamp) public view returns (uint256) { function getMinutesDelta(uint256 _lastTimestamp) public view returns (uint256) {
// return (block.timestamp - _lastTimestamp) / 60; return (block.timestamp - _lastTimestamp) / 60;
// } }
//
// // Calculate and cache the demurrage value corresponding to the (period of the) time of the method call // // Calculate and cache the demurrage value corresponding to the (period of the) time of the method call
// function applyDemurrage() public returns (bool) { // function applyDemurrage() public returns (bool) {
// return applyDemurrageLimited(0); // return applyDemurrageLimited(0);
@ -354,30 +355,30 @@ contract DemurrageTokenSingleCap {
// emit Decayed(demurrageTimestamp, periodCount, lastDemurrageAmount, demurrageAmount); // emit Decayed(demurrageTimestamp, periodCount, lastDemurrageAmount, demurrageAmount);
// return true; // return true;
// } // }
//
// // Return timestamp of start of period threshold // Return timestamp of start of period threshold
// function getPeriodTimeDelta(uint256 _periodCount) public view returns (uint256) { function getPeriodTimeDelta(uint256 _periodCount) public view returns (uint256) {
// return periodStart + (_periodCount * periodDuration); return periodStart + (_periodCount * periodDuration);
// } }
//
// // Amount of demurrage cycles inbetween the current timestamp and the given target time // Amount of demurrage cycles inbetween the current timestamp and the given target time
// function demurrageCycles(uint256 _target) public view returns (uint256) { function demurrageCycles(uint256 _target) public view returns (uint256) {
// return (block.timestamp - _target) / 60; return (block.timestamp - _target) / 60;
// } }
//
// function isEmptyRedistribution(redistributionItem memory _redistribution) public pure returns(bool) { function isEmptyRedistribution(redistributionItem memory _redistribution) public pure returns(bool) {
// if (_redistribution.period > 0) { if (_redistribution.period > 0) {
// return false; return false;
// } }
// if (_redistribution.value > 0) { if (_redistribution.value > 0) {
// return false; return false;
// } }
// if (_redistribution.demurrage > 0) { if (_redistribution.demurrage > 0) {
// return false; return false;
// } }
// return true; return true;
// } }
//
// // Recalculate the demurrage modifier for the new period // // Recalculate the demurrage modifier for the new period
// // Note that the supply for the consecutive period will be taken at the time of code execution, and thus not necessarily at the time when the redistribution period threshold was crossed. // // Note that the supply for the consecutive period will be taken at the time of code execution, and thus not necessarily at the time when the redistribution period threshold was crossed.
// function changePeriod() public returns (bool) { // function changePeriod() public returns (bool) {
@ -425,21 +426,8 @@ contract DemurrageTokenSingleCap {
//// } //// }
//// return (valueFactor * _value) / growthResolutionFactor; //// return (valueFactor * _value) / growthResolutionFactor;
//// } //// }
//
// // Calculate a value reduced by demurrage by the given period
// function decayBy(uint256 _value, uint256 _period) public view returns (uint256) {
// uint256 valueFactor;
// uint256 truncatedTaxLevel;
//
// valueFactor = growthResolutionFactor;
// truncatedTaxLevel = taxLevel / nanoDivider;
//
// for (uint256 i = 0; i < _period; i++) {
// valueFactor = valueFactor - ((valueFactor * truncatedTaxLevel) / growthResolutionFactor);
// }
// return (valueFactor * _value) / growthResolutionFactor;
// }
// Calculate a value reduced by demurrage by the given period
function decayBy(uint256 _value, uint256 _period) public view returns (uint256) { function decayBy(uint256 _value, uint256 _period) public view returns (uint256) {
int128 valuePoint; int128 valuePoint;
int128 periodPoint; int128 periodPoint;
@ -456,11 +444,14 @@ contract DemurrageTokenSingleCap {
return ABDKMath64x64.toUInt(v); return ABDKMath64x64.toUInt(v);
} }
//
// // Inflates the given amount according to the current demurrage modifier // Inflates the given amount according to the current demurrage modifier
// function toBaseAmount(uint256 _value) public view returns (uint256) { function toBaseAmount(uint256 _value) public view returns (uint256) {
// return (_value * resolutionFactor) / (demurrageAmount * 10000000000); int128 r;
// } //return (_value * resolutionFactor) / (demurrageAmount * 10000000000);
r = ABDKMath64x64.mul(demurrageAmount, ABDKMath64x64.fromUInt(_value));
return ABDKMath64x64.toUInt(r);
}
// //
// // Implements ERC20, triggers tax and/or redistribution // // Implements ERC20, triggers tax and/or redistribution
// function approve(address _spender, uint256 _value) public returns (bool) { // function approve(address _spender, uint256 _value) public returns (bool) {
@ -544,46 +535,46 @@ contract DemurrageTokenSingleCap {
// //
// return true; // return true;
// } // }
//
// // Implements EIP173 // Implements EIP173
// function transferOwnership(address _newOwner) public returns (bool) { function transferOwnership(address _newOwner) public returns (bool) {
// require(msg.sender == owner); require(msg.sender == owner);
// newOwner = _newOwner; newOwner = _newOwner;
// } }
//
// // Implements OwnedAccepter // Implements OwnedAccepter
// function acceptOwnership() public returns (bool) { function acceptOwnership() public returns (bool) {
// address oldOwner; address oldOwner;
//
// require(msg.sender == newOwner); require(msg.sender == newOwner);
// oldOwner = owner; oldOwner = owner;
// owner = newOwner; owner = newOwner;
// newOwner = address(0); newOwner = address(0);
// emit OwnershipTransferred(oldOwner, owner); emit OwnershipTransferred(oldOwner, owner);
// } }
//
// // Explicitly and irretrievably burn tokens // Explicitly and irretrievably burn tokens
// // Only token minters can burn tokens // Only token minters can burn tokens
// function burn(uint256 _value) public { function burn(uint256 _value) public {
// require(minter[msg.sender]); require(minter[msg.sender]);
// require(_value <= account[msg.sender]); require(_value <= account[msg.sender]);
// uint256 _delta = toBaseAmount(_value); uint256 _delta = toBaseAmount(_value);
//
// applyDemurrage(); //applyDemurrage();
// decreaseBaseBalance(msg.sender, _delta); decreaseBaseBalance(msg.sender, _delta);
// burned += _value; burned += _value;
// emit Burn(msg.sender, _value); emit Burn(msg.sender, _value);
// } }
//
// // Implements ERC20 // Implements ERC20
// function totalSupply() public view returns (uint256) { function totalSupply() public view returns (uint256) {
// return supply - burned; return supply - burned;
// } }
//
// // Return total number of burned tokens // Return total number of burned tokens
// function totalBurned() public view returns (uint256) { function totalBurned() public view returns (uint256) {
// return burned; return burned;
// } }
// Implements EIP165 // Implements EIP165
function supportsInterface(bytes4 _sum) public pure returns (bool) { function supportsInterface(bytes4 _sum) public pure returns (bool) {