Compare commits

..

No commits in common. "dev-0.5.6" and "v0.3.3" have entirely different histories.

46 changed files with 181 additions and 2705 deletions

1
CAVEAT
View File

@ -1 +0,0 @@
The contract is intended for slow rates of decay (e.g. 2% per month). Very high levels of decay (2% per minute) will lead to overflows, and will need a more flexible implementation to support it.

View File

@ -1,10 +0,0 @@
all: python solidity doc
python:
make -C python
solidity:
make -C solidity
doc:
make -C doc/texinfo
readme:
make -C doc/texinfo readme
pandoc -f docbook -t gfm doc/texinfo/build/docbook.xml > README.md

448
README.md
View File

@ -1,405 +1,95 @@
# Overview # RedistributedDemurrageToken
de-mur-rage **this documentation is obsolete, will rewrite asap**
1: the detention of a ship by the freighter beyond the time allowed for loading, unloading, or sailing ## Use Case
* Network / Basic Income Token
2: a charge for detaining a ship, freight car, or truck * 100 Sarafu is distributed to anyone in Kenya after user validation by the owner of a faucet which mints new Sarafu.
* Validated users are those that validate their phone number in Kenya.
This ERC20 smart contract implementation for the EVM imposes a demurrage * A Sarafu holding tax aka ([demurrage](https://en.wikipedia.org/wiki/Demurrage_(currency))) of 0.000050105908373373% is charged from users per minute - such that over 1 month to total tax would be 2%.
on all held token balances. * After 1 week the total amount tax is distributed evenly out to _active_ users.
* any single transaction by a user within that week is considered _active_ (heartbeat)
The demurrage is a continuous value *decay*, subtracted from all * This is meant to result in a disincentivization to hold (hodl) the Sarafu token and increase its usage as a medium of exchange rather than a store of value.
balances every minute. * This token can be added to liquidity pools with other ERC20 tokens and or Community Inclusion Currencies (CICs) - and thereby act as a central network token and connect various tokens and CICs together.
* Example
Also. a time period is defined at contract creation time at which the - With a demurrage of 2% (net per month) and a reward period of 1 month - If there are 10 users all with balances of 1000 Sarafu and only 2 of them trade that month (assume they trade back and forth with no net balance change).
difference between held balances and the demurrage can be withdrawn to a - Then the resulting balances after one tax period of those two trading would be 1080 Sarafu while the remaining non-active users would be 980 Sarafu. If this behaviour continued in the next tax period, with the same two users only trading (with no net balance changes), they would have 1158.39999968 Sarafu and those users that are not trading would have their balances further reduced to 960.40 Sarafu. If this continued on ~forever those two active trading users would have the entire token supply and the non-trading users would eventually reach a zero balance.
pre-selected address, which in turn can redistribute that token value. - this example calculation for 3 tax periods can be found here: https://gitlab.com/grassrootseconomics/cic-docs/-/blob/master/demurrage-redist-sarafu.ods
In short: Everyone is taxed a little something every minute, and every
so often a decision is made on how to redistribute that tax.
## Features
- Continuous decay of all balances.
- Capture and redistribution of decayed balances.
- Per-minute decay resolution.
- Minting and burning of vouchers.
- Grant and revoke access to mint and burn vouchers.
- Voucher expiration (modifiable anytime after publishing).
- Supply cap (modifiable anytime after publishing).
- Constant gas usage across exponential calculations.
## Nomenclature ## Nomenclature
`Demurrage` * `Demurrage` aka Decay amount: A percentage of token supply that will be charged once per minute and evenly redistributed to _active_ users every Demurrage Period (minutes)
A percentage of token supply that will continuously be removed. * Base balance: The inflated balance of each user is stored for bookkeeping.
* Sink Token Address: Rounding errors and if no one trades the tax goes to this address
* Demurrage Period (minutes)- aka `period`: The number of minutes over which a user must be _active_ to receive tax-redistibution.
`Demurrage Period`
A period of time denominated in minutes after which demurraged amounts
are available for redistribution.
`Sink Account` ## Ownership
The intermediate beneficiary of the demurraged amount, which may or may
not redistribute value.
`Base balance` * Contract creator is owner
The inflated balance of each used which is stored for bookkeeping. * Ownership can be transferred
# Use Case
The use-case inspiring this implementation is in the context of issuance ## Mint
of a *voucher* representing a credit obligation of an *Issuer* or
*Association of Issuers*.
This voucher can be redeemed as payment for the products of the Issuer. * Owner can add minters and remove
- A faucet contract would be a minter and choose the amount of tokens to mint and distribute to new _validated_ users.
- The interface says the amount and is at the caller's discretion per contract call. _validation_ is outside of this contract.
* A minter can remove itself
* Minters can mint any amount
The Issuer is the entity legally obligated to redeem the voucher as
payment.
Introducing demurrage on this vehicle discourages *withholding* the ## Demurrage
voucher, for example for speculative advantage. * Holding Tax (`demurrage`) is applied when a **mint** or **transfer**; (it can also be triggered explicitly)
- Note that the token supply _stays the same_ but a virtual _balance output_ is created.
- Updates `demurrageModifier` which represents the accumulated tax value and is an exponential decay step (of size `demurrage`) for each minute that has passed.
- `demurrageModifier = (1-demurrage)^(minute_passed)`
- e.g. a `demurrage` of 2% after the 1st minute would be give a `demurrageModifier = (1-0.02)^1 = 0.98`.
- e.g. a `demurrage` after the 2nd minute would be give a `demurrageModifier = (1-0.02)^2 = 0.9604`.
* All client-facing values (_balance output_ , _transfer inputs_) are adjusted with `demurrageModifier`.
- e.g. `_balance output_ = user_balance - user_balance * demurrageModifier`
This also encourages increased *velocity* of voucher use.
## Example ## Redistribution
Given: * One redistribution entry is added to storage for each `period`;
- When `mint` is triggered, the new totalsupply is stored to the entry
- When `transfer` is triggered, and the account did not yet participate in the `period`, the entry's participant count is incremented.
* Account must have "participated" in a period to be redistribution beneficiary.
* Redistribution is applied when an account triggers a **transfer** for the first time in a new `period`;
- Check if user has participated in `period`. (_active_ user heartbeat)
- Each _active_ user balance in the `period` is increased by `(total supply at end of period * demurrageModifier ) / number_of_active_participants` via minting
- Participation field is zeroed out for that user.
* Fractions must be rounded down
- Remainder is "dust" and should be sent to a dedicated Sink Token Address.
- If no one is _active_ all taxes go to the Sink Token Address.
- 10 voucher holders.
- A total supply of 1000 tokens. ## Data structures
- Demurrage of 2% per 30 days (43200 minutes). * One word per `account`:
- bits 000-071: value
- bits 072-103: period
- bits 104-255: (Unused)
* One word per `redistributions` period:
- bits 000-031: period
- bits 032-103: supply
- bits 104-139: participant count
- bits 140-159: demurrage modifier
- bits 160-254: (Unused)
- bits 255: Set if individual redistribution amounts are fractions
- Redistribution period of 30 days (43200 minutes). ### Notes
If no trades are made, the resulting balances after one redistribution Accumulated demurrage modifier in `demurrageModifier` is 128 bit, but will be _truncated_ do 20 bits in `redistributions`. The 128 bit resolution is to used to reduce the impact of fractional drift of the long-term accumulation of the demurrage modifier. However, the demurrage snapshot values used in `redistributions` are parts-per-million and can be fully contained within a 20-bit value.
period of every user would be 98 Vouchers.
The Sink Address will have a balance of 20 vouchers after the same
period.
Note that after the redistribution the total of all balances will equal ## QA
the total minted amount.
Note that all accounts holding such vouchers are effected by demurrage * Basic python tests in place
(even the Sink Account, pending redistribution). * How to determine and generate sufficient test vectors, and how to adapt them to scripts.
* Audit sources?
# Smart contract ## Known issues
## Common interfaces * A `transferFrom` following an `approve` call, when called across period thresholds, may fail if margin to demurraged amount is insufficient.
The smart contract is written in solidity, compatible with 0.8.x.
It implements a number of interfaces both from the Ethereum (ERC)
standards aswell as the Community Inclusion Currency contract interface
suite.
### ERC standard interfaces
- [ERC20 - Token Standard](https://eips.ethereum.org/EIPS/eip-20)
- [ERC165 - Standard Interface
Detection](https://eips.ethereum.org/EIPS/eip-165)
- [ERC173 - Contract Ownership
Standard](https://eips.ethereum.org/EIPS/eip-173)
- [ERC5679 - Token Minting and Burning (as part of CIC.Minter and
CIC.Burner)](https://eips.ethereum.org/EIPS/eip-5679)
### CIC interfaces
- [Burner](https://git.grassecon.net/cicnet/cic-contracts/src/branch/master/solidity/Burner.sol)
- [Expire](https://git.grassecon.net/cicnet/cic-contracts/src/branch/master/solidity/Expire.sol)
- [Minter](https://git.grassecon.net/cicnet/cic-contracts/src/branch/master/solidity/Minter.sol)
- [Seal](https://git.grassecon.net/cicnet/cic-contracts/src/branch/master/solidity/Seal.sol)
- [Writer](https://git.grassecon.net/cicnet/cic-contracts/src/branch/master/solidity/Writer.sol)
## Dependencies
The token contract uses the
[ADBKMath](https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol)
library to calculate exponentials.
## Permissions
The smart contract defines three levels of access.
1. Voucher contract owner
2. Voucher minter
3. Voucher holder
### Contract owner
When the contract is published to the network, the signer account of the
publishing transaction will be the contract owner.
Contract ownership can be changed by the owner using the **ERC173**
standard interface.
### Minter
A minter has access to mint vouchers, and to burn vouchers from its own
balance.
Only the contract owner may mint, and may add and remove minters.
Minters may be added and removed using the **CIC Writer** interface, as
long as the `WRITER_STATE` seal is not set. See [Sealing the
contract](#seal_005fstate) for further details.
The contract owner is automatically a minter.
### Holder
Any address may hold vouchers, and transfer vouchers from their balance.
Minters and the contract owner are automatically token holders.
All token holders are subject to demurrage.
## Publishing the contract
The contract is published with the following arguments:
`name`
ERC20 voucher name
`symbol`
ERC20 voucher symbol
`decimals`
ERC20 decimal count
`decayLevel`
Level of decay per minute. See [Specifying
demurrage](#specifying_005fdemurrage) below for further details.
`periodMinutes`
Number of minutes between each time the demurraged value can be
withdrawn to the *Sink Account*. See [Withdrawing demurraged
value](#withdrawing) below for further details. The period may not be
altered.
`defaultSinkAddress`
The initial *Sink Address*. The address may be altered as long as the
`SINK_STATE` seal has not been set. See [Sealing the
contract](#seal_005fstate) for further details.
### Specifying demurrage
The *input parameter* to the contract is a 128-bit positive fixed-point
number, where the most significant 64 bits represent the integer part,
and the lower 64 bits represents the decimals part, each consecutive
lesser bit halving the value of the previous bit.
For example, The byte value `00000000 00000002 a0000000 00000000`,
representing a zero-stripped binary value of $10.101$. This translates
to the (base 10) decimal value $2.625$. The decimal part is calculated
as, from left to right: $(1 * 0.5) + (0 * 0.25) + (1 * 0.125)$.
#### Calculating the demurrage parameter
The minute granularity of the demurrage value is calculating using the
continuous decay function.
For example, for a demurrage of 2% per 30 days (43200 minutes), the
input value will be:
$(1-0.02)^(1/43200) ~ 0.99999953234484737109$
The decimal part of the fixed-point representation of this value is:
`fffff8276fb8cfff`
The input parameter becomes:
`0000000000000000ffffa957014dc7ff`
See [Tools](#tools) for additional help generating the necessary values.
Note that attempting to publish a voucher contract with no (zero)
demurrage will fail (if demurrage is not needed, use another contract).
## Using the contract
### Withdrawing demurrage
After each redistribution period, the demurraged value of that period
can be withdrawn to the currently defined *Sink Account*.
The demurrage is calculated as from the total supply of voucher at the
end of the period.
Withdrawal should happen implicitly duing normal operation of the
contract. See [Side-effects in state changes](#sideeffects).
To explicitly credit the *Sink Address* with the demurrage value after a
period has been exceeded, the `changePeriod()` (`8f1df6bc`) method can
be called.
### Setting voucher expiry
The effect of a voucher expiring is that all balances will be frozen,
and all state changes affecting token balances will be blocked.
Expiry is defined in terms of redistribution periods. For example, if
the redistribution period is 30 days, and the expity is 3, then the
voucher expires after 90 days.
The expiry takes effect immediately when the redistribution period time
has been exceeded.
When the contract is published, no expiry is set.
Expiry may be set after publishing using the `CIC.Expire` interface.
If the `EXPIRE_STATE` seal has been set, expiry may not be changed
further.
### Capping voucher supply
The effect of a voucher supply cap is that all `CIC.Minter` calls will
fail if the total supply after minting exceeds the defined supply cap.
The supply cap still allows vouchers to be minted after `CIC.Burn`
calls, provided that the previous condition holds.
To apply the supply cap, the method `setMaxSupply(uint256) (6f8b44b0)`
is used.
### Side-effects in state changes
All state changes involving voucher values implicitly execute two core
methods to ensure application of the demurrage and redistribution.
The two methods are:
`applyDemurrage() (731f237c)`
Calculates the demurrage modifier of all balances according to the
current timestamp.
`changePeriod() (8f1df6bc)`
If the previously executed period change does not match the current
period, the period is changed, and the *Sink Address* is credited with
the demurrage amount of the current total supply.
Both of these methods are *noop* if no demurrage or withdrawal is
pending, respectively.
Examples of state changes that execute these methods include
`ERC20.transfer(...)`, `ERC20.transferFrom(...)` and `CIC.mintTo(...)`.
### Sealing the contract
Certain mutable core parameters of the contract can be *sealed*, meaning
prevented from being modifier further.
Sealing is executed using the `CIC.Seal` interface.
The sealing of parameters is irreversible.
The sealable parameters are[^1]:
`WRITER_STATE`
The `CIC.Writer` interface is blocked. The effect of this is that no
more changes may be made to which accounts have minter permission.
`SINK_STATE`
After setting this seal, the *Sink Address* may not be changed.
`EXPIRY_STATE`
Prevents future changes to the voucher expiry date[^2].
`CAP_STATE`
Immediately prevents future voucher minting, regardless of permissions.
## Gas usage
Gas usage is constant regardless of the amount of time passed between
each execution of demurrage and redistribution period calculations.
## Caveats
A `ERC20.transferFrom(...)` following an `ERC20.approve(...)` call, when
called across period thresholds, may fail if margin to demurraged amount
is insufficient.
# Tools
When installed as a python package, `erc20-demurrage-token` installs the
`erc20-demurrage-token-publish` executable script, which can be used to
publish smart contract instances.
While the man page for the tool can be referred to for general
information of the tool usage, two argument flags warrant special
mention in the context of this documentation.
`--demurrage-level`
The percentage of demurrage in terms of the redistribution period,
defined as parts-per-million.
`--redistribution-period`
A numeric value denominated in *minutes* to define the redistribution
period of the voucher demurrage.
For example, to define a 2% demurrage value for a redistribution period
of 30 days (43200 minutes), the argument to the argument flags would be:
erc20-demurrage-token-publish --demurrage-level 20000 --redistribution-period 43200 ...
## Calculating fixed-point values
The `erc20-demurrage-token` package installs the python package `dexif`
as part of its dependencies.
This package in turn provides an epinymous command-line tool (`dexif`)
which converts decimal values to a 128-bit fixed-point value expected by
the contract constructor.
An example:
$ dexif 123.456
7b74bc6a7ef9db23ff
$ dexif -x 7b74bc6a7ef9db23ff
123.456
## Contract interaction with chainlib-eth
All smart contract tests are implementing using
[chainlib-eth](https://git.defalsify.org/chainlib-eth) from the
chaintool suite.
The `eth-encode` tool from the `chainlib-eth` python package may be a
convenient way to interact with contract features.
Some examples include:
# explicitly call changePeriod()
$ eth-encode --mode tx --signature changePeriod -e <contract_address> -y <key_file> ...
# Set the sink address seal (The integer value of the SINK_STATE flag is 2 at the time of writing)
$ eth-encode --mode tx --signature seal -e <contract_address> -y <key_file> ... u:2
# Query current sink address of contract
$ eth-encode --mode call --signature sinkAddress -e <contract_address> ...
[^1]: Please refer to the contract source code for the numeric values of
the state flags
[^2]: The `EXPIRY_STATE` is implicitly set after expiration.

View File

@ -1,8 +0,0 @@
- 0.1.3
* Snapshot supply for crossed redistribution thresholds before minting new tokens.
- 0.1.4
* Implement natural logarithm
- 0.1.5
* Port changes from SingleNocap to SingleCap
- 0.2.0
* Make decay resolutions configurable, to support high levels of decay.

View File

@ -1 +0,0 @@
0.2.0

View File

@ -1,4 +0,0 @@
doc:
makeinfo --html -o build index.texi
readme:
makeinfo --docbook -o build/docbook.xml index.texi

View File

@ -1,221 +0,0 @@
@node contract
@chapter Smart contract
@section Common interfaces
The smart contract is written in solidity, compatible with 0.8.x.
It implements a number of interfaces both from the Ethereum (ERC) standards aswell as the Community Inclusion Currency contract interface suite.
@subsection ERC standard interfaces
@itemize @bullet
@item
@uref{https://eips.ethereum.org/EIPS/eip-20, ERC20 - Token Standard}
@item
@uref{https://eips.ethereum.org/EIPS/eip-165, ERC165 - Standard Interface Detection}
@item
@uref{https://eips.ethereum.org/EIPS/eip-173, ERC173 - Contract Ownership Standard}
@item
@uref{https://eips.ethereum.org/EIPS/eip-5679, ERC5679 - Token Minting and Burning (as part of CIC.Minter and CIC.Burner)}
@end itemize
@subsection CIC interfaces
@itemize @bullet
@item
@uref{https://git.grassecon.net/cicnet/cic-contracts/src/branch/master/solidity/Burner.sol, Burner}
@item
@uref{https://git.grassecon.net/cicnet/cic-contracts/src/branch/master/solidity/Expire.sol, Expire}
@item
@uref{https://git.grassecon.net/cicnet/cic-contracts/src/branch/master/solidity/Minter.sol, Minter}
@item
@uref{https://git.grassecon.net/cicnet/cic-contracts/src/branch/master/solidity/Seal.sol, Seal}
@item
@uref{https://git.grassecon.net/cicnet/cic-contracts/src/branch/master/solidity/Writer.sol, Writer}
@end itemize
@section Dependencies
The token contract uses the @url{https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol, ADBKMath} library to calculate exponentials.
@section Permissions
The smart contract defines three levels of access.
@enumerate
@item Voucher contract owner
@item Voucher minter
@item Voucher holder
@end enumerate
@subsection Contract owner
When the contract is published to the network, the signer account of the publishing transaction will be the contract owner.
Contract ownership can be changed by the owner using the @strong{ERC173} standard interface.
@subsection Minter
A minter has access to mint vouchers, and to burn vouchers from its own balance.
Only the contract owner may mint, and may add and remove minters. Minters may be added and removed using the @strong{CIC Writer} interface, as long as the @code{WRITER_STATE} seal is not set. @xref{seal_state, Sealing the contract} for further details.
The contract owner is automatically a minter.
@subsection Holder
Any address may hold vouchers, and transfer vouchers from their balance.
Minters and the contract owner are automatically token holders.
All token holders are subject to demurrage.
@section Publishing the contract
The contract is published with the following arguments:
@table @samp
@item name
ERC20 voucher name
@item symbol
ERC20 voucher symbol
@item decimals
ERC20 decimal count
@item decayLevel
Level of decay per minute. @xref{specifying_demurrage, Specifying demurrage} below for further details.
@item periodMinutes
Number of minutes between each time the demurraged value can be withdrawn to the @emph{Sink Account}. @xref{withdrawing, Withdrawing demurraged value} below for further details. The period may not be altered.
@item defaultSinkAddress
The initial @emph{Sink Address}. The address may be altered as long as the @code{SINK_STATE} seal has not been set. @xref{seal_state, Sealing the contract} for further details.
@end table
@node specifying_demurrage
@subsection Specifying demurrage
The @emph{input parameter} to the contract is a 128-bit positive fixed-point number, where the most significant 64 bits represent the integer part, and the lower 64 bits represents the decimals part, each consecutive lesser bit halving the value of the previous bit.
For example, The byte value @code{00000000 00000002 a0000000 00000000}, representing a zero-stripped binary value of @math{10.101}. This translates to the (base 10) decimal value @math{2.625}. The decimal part is calculated as, from left to right: @math{(1 * 0.5) + (0 * 0.25) + (1 * 0.125)}.
@subsubsection Calculating the demurrage parameter
The minute granularity of the demurrage value is calculating using the continuous decay function.
For example, for a demurrage of 2% per 30 days (43200 minutes), the input value will be:
@math{(1-0.02)^(1/43200) ~ 0.99999953234484737109}
The decimal part of the fixed-point representation of this value is:
@code{fffff8276fb8cfff}
The input parameter becomes:
@code{0000000000000000ffffa957014dc7ff}
@xref{tools, Tools} for additional help generating the necessary values.
Note that attempting to publish a voucher contract with no (zero) demurrage will fail (if demurrage is not needed, use another contract).
@section Using the contract
@node withdrawing
@subsection Withdrawing demurrage
After each redistribution period, the demurraged value of that period can be withdrawn to the currently defined @emph{Sink Account}.
The demurrage is calculated as from the total supply of voucher at the end of the period.
Withdrawal should happen implicitly duing normal operation of the contract. @xref{sideeffects, Side-effects in state changes}.
To explicitly credit the @emph{Sink Address} with the demurrage value after a period has been exceeded, the @code{changePeriod()} (@code{8f1df6bc}) method can be called.
@node expiry
@subsection Setting voucher expiry
The effect of a voucher expiring is that all balances will be frozen, and all state changes affecting token balances will be blocked.
Expiry is defined in terms of redistribution periods. For example, if the redistribution period is 30 days, and the expity is 3, then the voucher expires after 90 days.
The expiry takes effect immediately when the redistribution period time has been exceeded.
When the contract is published, no expiry is set.
Expiry may be set after publishing using the @code{CIC.Expire} interface.
If the @code{EXPIRE_STATE} seal has been set, expiry may not be changed further.
@node supply
@subsection Capping voucher supply
The effect of a voucher supply cap is that all @code{CIC.Minter} calls will fail if the total supply after minting exceeds the defined supply cap.
The supply cap still allows vouchers to be minted after @code{CIC.Burn} calls, provided that the previous condition holds.
To apply the supply cap, the method @code{setMaxSupply(uint256) (6f8b44b0)} is used.
@node sideeffects
@subsection Side-effects in state changes
All state changes involving voucher values implicitly execute two core methods to ensure application of the demurrage and redistribution.
The two methods are:
@table @code
@item applyDemurrage() (731f237c)
Calculates the demurrage modifier of all balances according to the current timestamp.
@item changePeriod() (8f1df6bc)
If the previously executed period change does not match the current period, the period is changed, and the @emph{Sink Address} is credited with the demurrage amount of the current total supply.
@end table
Both of these methods are @emph{noop} if no demurrage or withdrawal is pending, respectively.
Examples of state changes that execute these methods include @code{ERC20.transfer(...)}, @code{ERC20.transferFrom(...)} and @code{CIC.mintTo(...)}.
@node seal_state
@subsection Sealing the contract
Certain mutable core parameters of the contract can be @emph{sealed}, meaning prevented from being modifier further.
Sealing is executed using the @code{CIC.Seal} interface.
The sealing of parameters is irreversible.
The sealable parameters are@footnote{Please refer to the contract source code for the numeric values of the state flags}:
@table @code
@item WRITER_STATE
The @code{CIC.Writer} interface is blocked. The effect of this is that no more changes may be made to which accounts have minter permission.
@item SINK_STATE
After setting this seal, the @emph{Sink Address} may not be changed.
@item EXPIRY_STATE
Prevents future changes to the voucher expiry date@footnote{The @code{EXPIRY_STATE} is implicitly set after expiration.}.
@item CAP_STATE
Immediately prevents future voucher minting, regardless of permissions.
@end table
@section Gas usage
Gas usage is constant regardless of the amount of time passed between each execution of demurrage and redistribution period calculations.
@section Caveats
A @code{ERC20.transferFrom(...)} following an @code{ERC20.approve(...)} call, when called across period thresholds, may fail if margin to demurraged amount is insufficient.

View File

@ -1,29 +0,0 @@
\input texinfo
@settitle ERC20 Demurrage Token
@copying
Released 2023 under AGPL3
@end copying
@titlepage
@title ERC20 Demurrage Token
@author Louis Holbrook
@end titlepage
@c
@contents
@ifnottex
@node Top
@top Introduction
@end ifnottex
@menu
* overview ::
* instructions :
@end menu
@include overview.texi
@include usecase.texi
@include contract.texi
@include tools.texi

View File

@ -1,47 +0,0 @@
@node overview
@chapter Overview
@verbatim
de-mur-rage
1: the detention of a ship by the freighter beyond the time allowed for loading, unloading, or sailing
2: a charge for detaining a ship, freight car, or truck
@end verbatim
This ERC20 smart contract implementation for the EVM imposes a demurrage on all held token balances.
The demurrage is a continuous value @emph{decay}, subtracted from all balances every minute.
Also. a time period is defined at contract creation time at which the difference between held balances and the demurrage can be withdrawn to a pre-selected address, which in turn can redistribute that token value.
In short: Everyone is taxed a little something every minute, and every so often a decision is made on how to redistribute that tax.
@section Features
@itemize
@item Continuous decay of all balances.
@item Capture and redistribution of decayed balances.
@item Per-minute decay resolution.
@item Minting and burning of vouchers.
@item Grant and revoke access to mint and burn vouchers.
@item Voucher expiration (modifiable anytime after publishing).
@item Supply cap (modifiable anytime after publishing).
@item Constant gas usage across exponential calculations.
@end itemize
@section Nomenclature
@table @samp
@item Demurrage
A percentage of token supply that will continuously be removed.
@item Demurrage Period
A period of time denominated in minutes after which demurraged amounts are available for redistribution.
@item Sink Account
The intermediate beneficiary of the demurraged amount, which may or may not redistribute value.
@item Base balance
The inflated balance of each used which is stored for bookkeeping.
@end table

View File

@ -1,57 +0,0 @@
@node tools
@chapter Tools
When installed as a python package, @code{erc20-demurrage-token} installs the @code{erc20-demurrage-token-publish} executable script, which can be used to publish smart contract instances.
While the man page for the tool can be referred to for general information of the tool usage, two argument flags warrant special mention in the context of this documentation.
@table @code
@item --demurrage-level
The percentage of demurrage in terms of the redistribution period, defined as parts-per-million.
@item --redistribution-period
A numeric value denominated in @emph{minutes} to define the redistribution period of the voucher demurrage.
@end table
For example, to define a 2% demurrage value for a redistribution period of 30 days (43200 minutes), the argument to the argument flags would be:
@verbatim
erc20-demurrage-token-publish --demurrage-level 20000 --redistribution-period 43200 ...
@end verbatim
@section Calculating fixed-point values
The @code{erc20-demurrage-token} package installs the python package @code{dexif} as part of its dependencies.
This package in turn provides an epinymous command-line tool (@code{dexif}) which converts decimal values to a 128-bit fixed-point value expected by the contract constructor.
An example:
@example
$ dexif 123.456
7b74bc6a7ef9db23ff
$ dexif -x 7b74bc6a7ef9db23ff
123.456
@end example
@section Contract interaction with chainlib-eth
All smart contract tests are implementing using @url{https://git.defalsify.org/chainlib-eth, chainlib-eth} from the chaintool suite.
The @code{eth-encode} tool from the @code{chainlib-eth} python package may be a convenient way to interact with contract features.
Some examples include:
@example
# explicitly call changePeriod()
$ eth-encode --mode tx --signature changePeriod -e <contract_address> -y <key_file> ...
# Set the sink address seal (The integer value of the SINK_STATE flag is 2 at the time of writing)
$ eth-encode --mode tx --signature seal -e <contract_address> -y <key_file> ... u:2
# Query current sink address of contract
$ eth-encode --mode call --signature sinkAddress -e <contract_address> ...
@end example

View File

@ -1,32 +0,0 @@
@node usecase
@chapter Use Case
The use-case inspiring this implementation is in the context of issuance of a @emph{voucher} representing a credit obligation of an @emph{Issuer} or @emph{Association of Issuers}.
This voucher can be redeemed as payment for the products of the Issuer.
The Issuer is the entity legally obligated to redeem the voucher as payment.
Introducing demurrage on this vehicle discourages @emph{withholding} the voucher, for example for speculative advantage.
This also encourages increased @emph{velocity} of voucher use.
@section Example
Given:
@itemize
@item 10 voucher holders.
@item A total supply of 1000 tokens.
@item Demurrage of 2% per 30 days (43200 minutes).
@item Redistribution period of 30 days (43200 minutes).
@end itemize
If no trades are made, the resulting balances after one redistribution period of every user would be 98 Vouchers.
The Sink Address will have a balance of 20 vouchers after the same period.
Note that after the redistribution the total of all balances will equal the total minted amount.
Note that all accounts holding such vouchers are effected by demurrage (even the Sink Account, pending redistribution).

View File

@ -1,26 +1,3 @@
- 0.5.5
* Make allowance method public
- 0.5.4
* Add Transfer() event emission to sweep() in contract
- 0.5.3
* Add texinfo documentation
* Add man page for publish tool
- 0.5.2
* Update ERC165 interface response for Expire
* Add ExpiryChange event
- 0.5.1
* Update ERC165 interface responses
- 0.5.0
* Change license
- 0.4.2
* Correct burn interface implementation
- 0.4.1
* Eliminate solidity compiler warnings
- 0.4.0
* Rename taxLevel to decayLevel in contract
* Add sweep contract method to fully empty one account into another
- 0.3.6
* Reinstate owner as minter by default
- 0.3.0 - 0.3.0
* Smart contracts use abdk math libraries, all exponential operations are static gas cost * Smart contracts use abdk math libraries, all exponential operations are static gas cost
* Add expiry features, after which balances are frozen and no more transfers or demurrage will occur * Add expiry features, after which balances are frozen and no more transfers or demurrage will occur
@ -28,12 +5,6 @@
* Deployer script now takes demurrage amount as ppm instead of literal growth fraction * Deployer script now takes demurrage amount as ppm instead of literal growth fraction
* Retire old multi and cap contracts * Retire old multi and cap contracts
* Replace contract bitfields for redistributions with structs * Replace contract bitfields for redistributions with structs
- 0.2.0
* Add token burn function
* Fix gas leak when calculating decay on period change
* Remove all but SingleNocap contract in make install
* Make approve explicitly set value
* Add increaseAllowance and decreaseAllowance methods
- 0.1.1 - 0.1.1
* Settable demurrage steps for apply demurrage cli tool * Settable demurrage steps for apply demurrage cli tool
- 0.1.0 - 0.1.0

View File

@ -1,661 +0,0 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.

View File

@ -1 +1 @@
include erc20_demurrage_token/data/* erc20_demurrage_token/data/config/*.ini *requirements.txt man/build/*.1 include erc20_demurrage_token/data/* erc20_demurrage_token/data/config/*.ini *requirements.txt

View File

@ -1,8 +0,0 @@
all: pypi man
pypi:
python setup.py sdist
man:
mkdir -vp man/build
chainlib-man.py -b 0x3fafff -d man/build -n erc20-demurrage-token-publish -v man

View File

@ -3,6 +3,3 @@ from .token import (
DemurrageTokenSettings, DemurrageTokenSettings,
DemurrageRedistribution, DemurrageRedistribution,
) )
from .token import create
from .token import bytecode
from .token import args

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

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,176 +0,0 @@
"""Deploy sarafu token
.. moduleauthor:: Louis Holbrook <dev@holbrook.no>
.. pgp:: 0826EDA1702D1E87C6E2875121D2E7BB88C2A746
"""
# standard imports
import sys
import os
import json
import argparse
import logging
# external imports
import confini
from funga.eth.signer import EIP155Signer
from funga.eth.keystore.dict import DictKeystore
from chainlib.chain import ChainSpec
from chainlib.eth.nonce import (
RPCNonceOracle,
OverrideNonceOracle,
)
from chainlib.eth.gas import (
RPCGasOracle,
OverrideGasOracle,
)
from chainlib.eth.connection import EthHTTPConnection
from chainlib.eth.tx import receipt
from chainlib.eth.constant import ZERO_ADDRESS
import chainlib.eth.cli
from chainlib.eth.cli.arg import (
Arg,
ArgFlag,
process_args,
)
from chainlib.eth.cli.config import (
Config,
process_config,
)
from chainlib.eth.cli.log import process_log
from chainlib.eth.settings import process_settings
from chainlib.eth.address import to_checksum_address
from chainlib.settings import ChainSettings
from dexif import to_fixed
# local imports
import erc20_demurrage_token
from erc20_demurrage_token import (
DemurrageToken,
DemurrageTokenSettings,
)
logg = logging.getLogger()
script_dir = os.path.dirname(__file__)
data_dir = os.path.join(script_dir, '..', 'data')
config_dir = os.path.join(data_dir, 'config')
def process_config_local(config, arg, args, flags):
config.add(args.token_name, 'TOKEN_NAME')
config.add(args.token_symbol, 'TOKEN_SYMBOL')
config.add(args.token_decimals, 'TOKEN_DECIMALS')
sink_address = to_checksum_address(args.sink_address)
config.add(sink_address, 'TOKEN_SINK_ADDRESS')
config.add(args.redistribution_period, 'TOKEN_REDISTRIBUTION_PERIOD')
v = (1 - (args.demurrage_level / 1000000)) ** (1 / config.get('TOKEN_REDISTRIBUTION_PERIOD'))
if v >= 1.0:
raise ValueError('demurrage level must be less than 100%')
demurrage_level = to_fixed(v)
logg.info('v {} demurrage level {}'.format(v, demurrage_level))
config.add(demurrage_level, 'TOKEN_DEMURRAGE_LEVEL')
return config
arg_flags = ArgFlag()
arg = Arg(arg_flags)
flags = arg_flags.STD_WRITE | arg_flags.WALLET
argparser = chainlib.eth.cli.ArgumentParser(arg_flags)
argparser = process_args(argparser, arg, flags)
argparser.add_argument('--name', dest='token_name', type=str, help='Token name')
argparser.add_argument('--symbol', dest='token_symbol', required=True, type=str, help='Token symbol')
argparser.add_argument('--decimals', dest='token_decimals', type=int, help='Token decimals')
argparser.add_argument('--sink-address', dest='sink_address', type=str, help='demurrage level,ppm per minute')
argparser.add_argument('--redistribution-period', type=int, help='redistribution period, minutes (0 = deactivate)') # default 10080 = week
argparser.add_argument('--demurrage-level', dest='demurrage_level', type=int, help='demurrage level, ppm per period')
args = argparser.parse_args()
logg = process_log(args, logg)
config = Config()
config = process_config(config, arg, args, flags)
config = process_config_local(config, arg, args, flags)
logg.debug('config loaded:\n{}'.format(config))
settings = ChainSettings()
settings = process_settings(settings, config)
logg.debug('settings loaded:\n{}'.format(settings))
#extra_args = {
# 'redistribution_period': 'TOKEN_REDISTRIBUTION_PERIOD',
# 'demurrage_level': 'TOKEN_DEMURRAGE_LEVEL',
# 'supply_limit': 'TOKEN_SUPPLY_LIMIT',
# 'token_name': 'TOKEN_NAME',
# 'token_symbol': 'TOKEN_SYMBOL',
# 'token_decimals': 'TOKEN_DECIMALS',
# 'sink_address': 'TOKEN_SINK_ADDRESS',
# 'multi': None,
# }
#config = chainlib.eth.cli.Config.from_args(args, arg_flags, extra_args=extra_args, default_fee_limit=DemurrageToken.gas(), base_config_dir=config_dir)
#
#if not bool(config.get('TOKEN_NAME')):
# logg.info('token name not set, using symbol {} as name'.format(config.get('TOKEN_SYMBOL')))
# config.add(config.get('TOKEN_SYMBOL'), 'TOKEN_NAME', True)
#
#if config.get('TOKEN_SUPPLY_LIMIT') == None:
# config.add(0, 'TOKEN_SUPPLY_LIMIT', True)
#
#if config.get('TOKEN_REDISTRIBUTION_PERIOD') == None:
# config.add(10800, 'TOKEN_REDISTRIBUTION_PERIOD', True)
#logg.debug('config loaded:\n{}'.format(config))
#
#wallet = chainlib.eth.cli.Wallet()
#wallet.from_config(config)
#
#rpc = chainlib.eth.cli.Rpc(wallet=wallet)
#conn = rpc.connect_by_config(config)
#
#chain_spec = ChainSpec.from_chain_str(config.get('CHAIN_SPEC'))
def main():
conn = settings.get('CONN')
c = DemurrageToken(
settings.get('CHAIN_SPEC'),
signer=settings.get('SIGNER'),
gas_oracle=settings.get('FEE_ORACLE'),
nonce_oracle=settings.get('NONCE_ORACLE'),
)
token_settings = DemurrageTokenSettings()
token_settings.name = config.get('TOKEN_NAME')
token_settings.symbol = config.get('TOKEN_SYMBOL')
token_settings.decimals = int(config.get('TOKEN_DECIMALS'))
token_settings.demurrage_level = int(config.get('TOKEN_DEMURRAGE_LEVEL'))
token_settings.period_minutes = int(config.get('TOKEN_REDISTRIBUTION_PERIOD'))
token_settings.sink_address = config.get('TOKEN_SINK_ADDRESS')
(tx_hash_hex, o) = c.constructor(
settings.get('SENDER_ADDRESS'),
token_settings,
)
if settings.get('RPC_SEND'):
conn.do(o)
if config.true('_WAIT'):
r = conn.wait(tx_hash_hex)
if r['status'] == 0:
sys.stderr.write('EVM revert while deploying contract. Wish I had more to tell you')
sys.exit(1)
# TODO: pass through translator for keys (evm tester uses underscore instead of camelcase)
address = r['contractAddress']
print(address)
else:
print(tx_hash_hex)
else:
print(o)
if __name__ == '__main__':
main()

View File

@ -1 +0,0 @@
wor@gecon.733148:1676287007

View File

@ -68,11 +68,10 @@ def process_config_local(config, arg, args, flags):
config.add(sink_address, 'TOKEN_SINK_ADDRESS') config.add(sink_address, 'TOKEN_SINK_ADDRESS')
config.add(args.redistribution_period, 'TOKEN_REDISTRIBUTION_PERIOD') config.add(args.redistribution_period, 'TOKEN_REDISTRIBUTION_PERIOD')
v = (1 - (args.demurrage_level / 1000000)) ** (1 / config.get('TOKEN_REDISTRIBUTION_PERIOD')) v = args.demurrage_level / 1000000
if v >= 1.0: if v >= 1.0:
raise ValueError('demurrage level must be less than 100%') raise ValueError('demurrage level must be less than 100%')
demurrage_level = to_fixed(v) demurrage_level = to_fixed(v)
logg.info('v {} demurrage level {}'.format(v, demurrage_level))
config.add(demurrage_level, 'TOKEN_DEMURRAGE_LEVEL') config.add(demurrage_level, 'TOKEN_DEMURRAGE_LEVEL')
return config return config

View File

@ -78,34 +78,28 @@ class DemurrageToken(ERC20, SealedContract, ExpiryContract):
__abi = {} __abi = {}
__bytecode = {} __bytecode = {}
def constructor(self, sender_address, settings, tx_format=TxFormat.JSONRPC, version=None): def constructor(self, sender_address, settings, tx_format=TxFormat.JSONRPC):
code = self.cargs(settings.name, settings.symbol, settings.decimals, settings.demurrage_level, settings.period_minutes, settings.sink_address, version=version) code = DemurrageToken.bytecode()
enc = ABIContractEncoder()
enc.string(settings.name)
enc.string(settings.symbol)
enc.uint256(settings.decimals)
enc.uint256(settings.demurrage_level)
enc.uint256(settings.period_minutes)
enc.address(settings.sink_address)
code += enc.get()
tx = self.template(sender_address, None, use_nonce=True) tx = self.template(sender_address, None, use_nonce=True)
tx = self.set_code(tx, code) tx = self.set_code(tx, code)
return self.finalize(tx, tx_format) return self.finalize(tx, tx_format)
@staticmethod
def cargs(name, symbol, decimals, demurrage_level, period_minutes, sink_address, version=None):
code = DemurrageToken.bytecode()
enc = ABIContractEncoder()
enc.string(name)
enc.string(symbol)
enc.uint256(decimals)
enc.uint256(demurrage_level)
enc.uint256(period_minutes)
enc.address(sink_address)
code += enc.get()
return code
@staticmethod @staticmethod
def gas(code=None): def gas(code=None):
return 7000000 return 4000000
@staticmethod @staticmethod
def abi(): def abi(multi=True):
name = 'DemurrageTokenSingleNocap' name = 'DemurrageTokenSingleNocap'
if DemurrageToken.__abi.get(name) == None: if DemurrageToken.__abi.get(name) == None:
f = open(os.path.join(data_dir, name + '.json'), 'r') f = open(os.path.join(data_dir, name + '.json'), 'r')
@ -115,7 +109,7 @@ class DemurrageToken(ERC20, SealedContract, ExpiryContract):
@staticmethod @staticmethod
def bytecode(version=None): def bytecode(multi=True):
name = 'DemurrageTokenSingleNocap' name = 'DemurrageTokenSingleNocap'
if DemurrageToken.__bytecode.get(name) == None: if DemurrageToken.__bytecode.get(name) == None:
f = open(os.path.join(data_dir, name + '.bin'), 'r') f = open(os.path.join(data_dir, name + '.bin'), 'r')
@ -443,19 +437,6 @@ class DemurrageToken(ERC20, SealedContract, ExpiryContract):
return tx return tx
def sweep(self, contract_address, sender_address, recipient_address, tx_format=TxFormat.JSONRPC):
enc = ABIContractEncoder()
enc.method('sweep')
enc.typ(ABIContractType.ADDRESS)
enc.address(recipient_address)
data = enc.get()
tx = self.template(sender_address, contract_address, use_nonce=True)
tx = self.set_code(tx, data)
tx = self.finalize(tx, tx_format)
return tx
def apply_demurrage(self, contract_address, sender_address, limit=0, tx_format=TxFormat.JSONRPC): def apply_demurrage(self, contract_address, sender_address, limit=0, tx_format=TxFormat.JSONRPC):
if limit == 0: if limit == 0:
return self.transact_noarg('applyDemurrage', contract_address, sender_address) return self.transact_noarg('applyDemurrage', contract_address, sender_address)
@ -487,8 +468,10 @@ class DemurrageToken(ERC20, SealedContract, ExpiryContract):
return tx return tx
def decay_level(self, contract_address, sender_address=ZERO_ADDRESS):
return self.call_noarg('decayLevel', contract_address, sender_address=sender_address)
def tax_level(self, contract_address, sender_address=ZERO_ADDRESS):
return self.call_noarg('taxLevel', contract_address, sender_address=sender_address)
def resolution_factor(self, contract_address, sender_address=ZERO_ADDRESS): def resolution_factor(self, contract_address, sender_address=ZERO_ADDRESS):
@ -669,7 +652,7 @@ class DemurrageToken(ERC20, SealedContract, ExpiryContract):
@classmethod @classmethod
def parse_decay_level(self, v): def parse_tax_level(self, v):
return abi_decode_single(ABIContractType.UINT256, v) return abi_decode_single(ABIContractType.UINT256, v)
@ -682,25 +665,3 @@ class DemurrageToken(ERC20, SealedContract, ExpiryContract):
def parse_total_burned(self, v): def parse_total_burned(self, v):
return abi_decode_single(ABIContractType.UINT256, v) return abi_decode_single(ABIContractType.UINT256, v)
def bytecode(**kwargs):
return DemurrageToken.bytecode(version=kwargs.get('version'))
def create(**kwargs):
return DemurrageToken.cargs(
kwargs['name'],
kwargs['symbol'],
kwargs['decimals'],
kwargs['demurragelevel'],
kwargs['redistributionperiod'],
kwargs['sinkaddress'],
version=kwargs.get('version'))
def args(v):
if v == 'create':
return (['name', 'symbol', 'decimals', 'demurragelevel', 'redistributionperiod', 'sinkaddress'], ['version'],)
elif v == 'default' or v == 'bytecode':
return ([], ['version'],)
raise ValueError('unknown command: ' + v)

View File

@ -61,10 +61,10 @@ class TestTokenDeploy:
self.start_time = int(r['timestamp']) self.start_time = int(r['timestamp'])
def publish(self, rpc, publisher_address, interface, supply_cap=0): def deploy(self, rpc, deployer_address, interface, supply_cap=0):
tx_hash = None tx_hash = None
o = None o = None
(tx_hash, o) = interface.constructor(publisher_address, self.settings) (tx_hash, o) = interface.constructor(deployer_address, self.settings)
r = rpc.do(o) r = rpc.do(o)
o = receipt(tx_hash) o = receipt(tx_hash)
@ -77,6 +77,12 @@ class TestTokenDeploy:
r = rpc.do(o) r = rpc.do(o)
self.start_time = r['timestamp'] self.start_time = r['timestamp']
(tx_hash, o) = interface.add_writer(self.address, deployer_address, deployer_address)
r = rpc.do(o)
o = receipt(tx_hash)
r = rpc.do(o)
assert r['status'] == 1
return self.address return self.address
@ -89,7 +95,7 @@ class TestDemurrage(EthTesterCase):
period = getattr(self, 'period') period = getattr(self, 'period')
except AttributeError as e: except AttributeError as e:
pass pass
self.publisher = TestTokenDeploy(self.rpc, period=period, sink_address=self.accounts[9]) self.deployer = TestTokenDeploy(self.rpc, period=period, sink_address=self.accounts[9])
self.default_supply = 0 self.default_supply = 0
self.default_supply_cap = 0 self.default_supply_cap = 0
self.start_block = None self.start_block = None
@ -97,13 +103,13 @@ class TestDemurrage(EthTesterCase):
self.start_time = None self.start_time = None
def publish(self, interface): def deploy(self, interface):
self.address = self.publisher.publish(self.rpc, self.accounts[0], interface, supply_cap=self.default_supply_cap) self.address = self.deployer.deploy(self.rpc, self.accounts[0], interface, supply_cap=self.default_supply_cap)
self.start_block = self.publisher.start_block self.start_block = self.deployer.start_block
self.start_time = self.publisher.start_time self.start_time = self.deployer.start_time
self.tax_level = self.publisher.tax_level self.tax_level = self.deployer.tax_level
self.period_seconds = self.publisher.period_seconds self.period_seconds = self.deployer.period_seconds
self.sink_address = self.publisher.sink_address self.sink_address = self.deployer.sink_address
logg.debug('contract address {} start block {} start time {}'.format(self.address, self.start_block, self.start_time)) logg.debug('contract address {} start block {} start time {}'.format(self.address, self.start_block, self.start_time))
@ -119,13 +125,6 @@ class TestDemurrage(EthTesterCase):
raise AssertionError('{} not within lower {} and higher {}'.format(v, lower_target, higher_target)) raise AssertionError('{} not within lower {} and higher {}'.format(v, lower_target, higher_target))
def assert_within_greater(self, v, target, tolerance_ppm):
greater_target = target + (target * (tolerance_ppm / 1000000))
self.assertLessEqual(v, greater_target)
self.assertGreaterEqual(v, target)
logg.debug('asserted within greater {} >= {} >= {}'.format(greater_target, v, target))
def assert_within_lower(self, v, target, tolerance_ppm): def assert_within_lower(self, v, target, tolerance_ppm):
lower_target = target - (target * (tolerance_ppm / 1000000)) lower_target = target - (target * (tolerance_ppm / 1000000))
self.assertGreaterEqual(v, lower_target) self.assertGreaterEqual(v, lower_target)
@ -151,7 +150,7 @@ class TestDemurrageDefault(TestDemurrage):
nonce_oracle = RPCNonceOracle(self.accounts[0], self.rpc) nonce_oracle = RPCNonceOracle(self.accounts[0], self.rpc)
c = DemurrageToken(self.chain_spec, signer=self.signer, nonce_oracle=nonce_oracle) c = DemurrageToken(self.chain_spec, signer=self.signer, nonce_oracle=nonce_oracle)
self.publish(c) self.deploy(c)
self.default_supply = 10**12 self.default_supply = 10**12
self.default_supply_cap = self.default_supply self.default_supply_cap = self.default_supply

View File

@ -1,218 +0,0 @@
.TH erc20-demurrage-token-publish 1
.SH NAME
erc20-demurrage-token-publish \- Publishing tool for the ERC20 Demurrage Token smart contract.
.SH SYNOPSIS
.SY erc20-demurrage-token-publish
.RI --name NAME --symbol SYMBOL --decimals DECIMALS --demurrage-level PPM --redistribution-period MINUTES --sink-address ADDRESS
.YS
.SH DESCRIPTION
.P
This tool generates the appropriate bytecode to store the ERC20 Demurrage Token smartcontract code on an EVM chain, along with the required construction parameters.
Arguments for EVM encoding and interaction with EVM RPC node is handled by the \fBchainlib-eth\fP python package.
Specific arguments for this tool are the \fB--demurrage-level\fP, \fB--redistribution-period\fP and \fB--sink-address\fP arguments.
.SS OPTIONS
.TP
\fB-0\fP
Omit newline to output
.TP
\fB-c \fI\fIconfig_dir\fP\fP, \fB--config \fI\fIconfig_dir\fP\fP
Load configuration files from given directory. All files with an .ini extension will be loaded, of which all must contain valid ini file data.
.TP
\fB--demurrage-level \fI\fIlevel
\fP\fP
Level of decay per minute. See SPECIFYING DEMURRAGE below.
.TP
\fB--dumpconfig \fI\fIformat\fP\fP
Output configuration settings rendered from environment and inputs. Valid arguments are \fIini\fP for ini file output, and \fIenv\fP for environment variable output. See \fBCONFIGURATION\fP.
.TP
\fB-e\fP, \fB--executable-address\fP
Address of an executable code point on the network.
.TP
\fB--env-prefix\fP
Environment prefix for variables to overwrite configuration. Example: If \fB--env-prefix\fP is set to \fBFOO\fP then configuration variable \fBBAR_BAZ\fP would be set by environment variable \fBFOO_BAZ_BAR\fP. Also see \fBENVIRONMENT\fP.
.TP
\fB--fee-limit\fP
Set the limit of execution units for the transaction. If used with \fB-s\fP this may incur actual network token cost. If \fB--fee-price\fP is not explicitly set, the price \fImay\fP be retrieved from the network, and multiplied with this value to define the cost.
.TP
\fB--fee-price\fP
Set fee unit price to offer for the transaction. If used with \fB-s\fP this may incur actual network token cost.
.TP
\fB--height\fP
Block height at which to query state for. Does not apply to transactions.
.TP
\fB-i \fI\fIchain_spec\fP\fP, \fB--chain-spec \fI\fIchain_spec\fP\fP
Chain specification string, in the format <engine>:<fork>:<chain_id>:<common_name>. Example: "evm:london:1:ethereum". Overrides the \fIRPC_CREDENTIALS\fP configuration setting.
.TP
\fB-n \fI\fInamespace\fP\fP, \fB--namespace \fI\fInamespace\fP\fP
Load given configuration namespace. Configuration will be loaded from the immediate configuration subdirectory with the same name.
.TP
\fB--no-logs\fP
Turn of logging completely. Negates \fB-v\fP and \fB-vv\fP
.TP
\fB--nonce\fP
Explicitly set nonce to use for transaction.
.TP
\fB-p\fP, \fB--rpc-provider\fP
Fully-qualified URL of RPC provider. Overrides the \fIRPC_PROVIDER\fP configuration setting.
.TP
\fB--passphrase-file \fI\fIpath\fP\fP
Path to file containing password to unlock key file
.TP
\fB--raw\fP
Produce output most optimized for machines.
.TP
\fB--redistribution-period \fI\fIminutes
\fP\fP
Number of minuntes between each withdrawal of demurraged value is possible.
.TP
\fB--rpc-auth\fP
RPC endpoint authentication method, e.g. how to handle a HTTP WWW-Authenticate header. Overrides the \fIRPC_AUTH\fP configuration setting.
.TP
\fB--rpc-credentials\fP
RPC endpoint authentication data. Format depends on the authentication method defined in \fB--rpc-auth\fP. Overrides the \fIRPC_CREDENTIALS\fP configuration setting.
.TP
\fB--rpc-dialect\fP
RPC backend dialect. If specified it \fImay\fP help with encoding and decoding issues. Overrides the \fIRPC_DIALECT\fP configuration setting.
.TP
\fB-s\fP
Send to network. If set, network state may change. This means tokens may be spent and so on. Use with care. Only applies to transactions.
.TP
\fB--seq\fP
Use numeric sequencial jsonrpc query ids. Useful for buggy server implementations who expects such.
.TP
\fB--sink-address \fI\fIaddress
\fP\fP
Initial address receiving the demurrage value withdrawal.
.TP
\fB-u\fP, \fB--unsafe\fP
Allow addresses that do not pass checksum.
.TP
\fB-v\fP
Verbose. Show logs for important state changes.
.TP
\fB-vv\fP
Very verbose. Show logs with debugging information.
.TP
\fB-w\fP
Wait for the last transaction to be confirmed on the network. Will generate an error if the EVM execution fails.
.TP
\fB-ww\fP
Wait for \fIall\fP transactions sequentially to be confirmed on the network. Will generate an error if EVM execution fails for any of the transactions.
.TP
\fB-y \fI\fIpath\fP\fP, \fB--key-path \fI\fIpath\fP\fP
Path to signing key. Overrides the \fIWALLET_KEY_FILE\fP configuration setting.
.SH CONFIGURATION
All configuration settings may be overriden both by environment variables, or by overriding settings with the contents of ini-files in the directory defined by the \fB-c\fP option.
The active configuration, with values assigned from environment and arguments, can be output using the \fB--dumpconfig\fP \fIformat\fP option. Note that entries having keys prefixed with underscore (e.g. _SEQ) are not actual configuration settings, and thus cannot be overridden with environment variables.
To refer to a configuration setting by environment variables, the \fIsection\fP and \fIkey\fP are concatenated together with an underscore, and transformed to upper-case. For example, the configuration variable \fIFOO_BAZ_BAR\fP refers to an ini-file entry as follows:
.EX
[foo]
bar_baz = xyzzy
.EE
In the \fBENVIRONMENT\fP section below, the relevant configuration settings for this tool is listed along with a short description of its meaning.
Some configuration settings may also be overriden by command line options. Also note that the use of the \fB-n\fP and \fB--env-prefix\fP options affect how environment and configuration is read. The effects of options on how configuration settings are affective is described in the respective \fBOPTIONS\fP section.
.SH SPECIFYING DEMURRAGE
Demurrage is specified as a parts-per-million value in terms of the chosen \fI--redistribution-period\fP.
For example, a value of \fB20000\fP with a \fI--redistribution-period\fP of \fB43200\fP corresponds to a \fB2%\fP demurrage per \fB30\fP days.
.SH ENVIRONMENT
.TP
\fICHAIN_SPEC\fP
String specifying the type of chain connected to, in the format \fI<engine>:<fork>:<network_id>:<common_name>\fP. For EVM nodes the \fIengine\fP value will always be \fIevm\fP.
.TP
\fIRPC_AUTH\fP
Authentication method to use for the \fIRPC_PROVIDER\fP. Currently only \fIbasic\fP is supported.
.TP
\fIRPC_CREDENTIALS\fP
Authentication credentials to use for \fIRPC_AUTH\fP. For \fIbasic\fP authentication the value must be given as \fI<user>:<pass>\fP.
.TP
\fIRPC_DIALECT\fP
Enables translations of EVM node specific formatting and response codes.
.TP
\fIRPC_PROVIDER\fP
Fully-qualified URL to the RPC endpoint of the blockchain node.
.TP
\fIWALLET_KEY_FILE\fP
The wallet key file containing private key to use for transaction signing. Overridden by \fB-y\fP.
.TP
\fIWALLET_PASSPHRASE\fP
Passphrase to unlock wallet. \fBWARNING:\fP it is \fBunsafe\fP to pass the passphrase as an environment variable. If the key unlocks something of value, the passphrase should rather be in a configuration file, preferably as an encrypted entry. Alternatively, a passphrase can be read from file using the \fB--passphrase-file\fP option. Files containing passphrases should only be accessible by the owner.
.SH LICENSE
This documentation and its source is licensed under the Creative Commons Attribution-Sharealike 4.0 International license.
The source code of the tool this documentation describes is licensed under the GNU General Public License 3.0.
.SH COPYRIGHT
Louis Holbrook <dev@holbrook.no> (https://holbrook.no)
PGP: 59A844A484AC11253D3A3E9DCDCBD24DD1D0E001
.SH SOURCE CODE
https://git.defalsify.org
.SH SEE ALSO
.BP
confini-dump(1), eth-keyfile(1)

View File

@ -1,5 +0,0 @@
.SH SPECIFYING DEMURRAGE
Demurrage is specified as a parts-per-million value in terms of the chosen \fI--redistribution-period\fP.
For example, a value of \fB20000\fP with a \fI--redistribution-period\fP of \fB43200\fP corresponds to a \fB2%\fP demurrage per \fB30\fP days.

View File

@ -1,22 +0,0 @@
.TH erc20-demurrage-token-publish 1
.SH NAME
erc20-demurrage-token-publish \- Publishing tool for the ERC20 Demurrage Token smart contract.
.SH SYNOPSIS
.SY erc20-demurrage-token-publish
.RI --name NAME --symbol SYMBOL --decimals DECIMALS --demurrage-level PPM --redistribution-period MINUTES --sink-address ADDRESS
.YS
.SH DESCRIPTION
.P
This tool generates the appropriate bytecode to store the ERC20 Demurrage Token smartcontract code on an EVM chain, along with the required construction parameters.
Arguments for EVM encoding and interaction with EVM RPC node is handled by the \fBchainlib-eth\fP python package.
Specific arguments for this tool are the \fB--demurrage-level\fP, \fB--redistribution-period\fP and \fB--sink-address\fP arguments.
.SS OPTIONS

View File

@ -1,3 +0,0 @@
demurragelevel Level of decay per minute. See SPECIFYING DEMURRAGE below. --demurrage-level level
redistributionperiod Number of minuntes between each withdrawal of demurraged value is possible. --redistribution-period minutes
sinkaddress Initial address receiving the demurrage value withdrawal. --sink-address address

View File

@ -1,5 +1,4 @@
chainlib-eth~=0.4.11 chainlib-eth~=0.4.11
chainlib~=0.4.12 eth-erc20~=0.5.0
eth-erc20~=0.7.0
funga-eth~=0.6.0 funga-eth~=0.6.0
dexif~=0.0.2 dexif~=0.0.1

View File

@ -1,10 +1,10 @@
[metadata] [metadata]
name = erc20-demurrage-token name = erc20-demurrage-token
version = 0.5.6 version = 0.3.3
description = ERC20 token with redistributed continual demurrage description = ERC20 token with redistributed continual demurrage
author = Louis Holbrook author = Louis Holbrook
author_email = dev@holbrook.no author_email = dev@holbrook.no
url = https://holbrook.no/src/erc20-demurrage-token/log.html url = https://gitlab.com/ccicnet/erc20-demurrage-token
keywords = keywords =
ethereum ethereum
blockchain blockchain
@ -13,20 +13,19 @@ keywords =
classifiers = classifiers =
Programming Language :: Python :: 3 Programming Language :: Python :: 3
Operating System :: OS Independent Operating System :: OS Independent
Development Status :: 4 - Beta Development Status :: 3 - Alpha
Environment :: Console Environment :: No Input/Output (Daemon)
Intended Audience :: Developers Intended Audience :: Developers
License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+) License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)
Topic :: Internet Topic :: Internet
Topic :: Software Development :: Libraries
#Topic :: Blockchain :: EVM #Topic :: Blockchain :: EVM
license = AGPLv3+ license = GPL3
licence_files = licence_files =
LICENSE LICENSE
[options] [options]
include_package_data = True include_package_data = True
python_requires = >= 3.8 python_requires = >= 3.7
packages = packages =
erc20_demurrage_token erc20_demurrage_token
erc20_demurrage_token.runnable erc20_demurrage_token.runnable

View File

@ -1,5 +1,4 @@
from setuptools import setup from setuptools import setup
import os
requirements = [] requirements = []
f = open('requirements.txt', 'r') f = open('requirements.txt', 'r')
@ -20,7 +19,6 @@ while True:
f.close() f.close()
man_dir = 'man/build'
setup( setup(
package_data={ package_data={
'': [ '': [
@ -30,8 +28,4 @@ setup(
include_package_data=True, include_package_data=True,
install_requires=requirements, install_requires=requirements,
tests_require=test_requirements, tests_require=test_requirements,
data_files=[("man/man1", [
os.path.join(man_dir, 'erc20-demurrage-token-publish.1'),
]
)],
) )

View File

@ -122,26 +122,5 @@ class TestAmounts(TestDemurrageDefault):
self.assert_within_lower(balance, case[1], 10000) self.assert_within_lower(balance, case[1], 10000)
def test_sweep(self):
nonce_oracle = RPCNonceOracle(self.accounts[0], self.rpc)
c = DemurrageToken(self.chain_spec, signer=self.signer, nonce_oracle=nonce_oracle)
(tx_hash, o) = c.mint_to(self.address, self.accounts[0], self.accounts[0], 2000)
r = self.rpc.do(o)
(tx_hash, o) = c.sweep(self.address, self.accounts[0], self.accounts[1])
self.rpc.do(o)
o = receipt(tx_hash)
r = self.rpc.do(o)
self.assertEqual(r['status'], 1)
o = c.balance_of(self.address, self.accounts[0], sender_address=self.accounts[0])
r = self.rpc.do(o)
self.assertEqual(c.parse_balance(r), 0)
o = c.balance_of(self.address, self.accounts[1], sender_address=self.accounts[0])
r = self.rpc.do(o)
self.assert_within(c.parse_balance(r), 2000, 1)
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()

View File

@ -308,30 +308,6 @@ class TestBasic(TestDemurrageDefault):
self.assertEqual(r['status'], 1) self.assertEqual(r['status'], 1)
def test_approve_max(self):
nonce_oracle = RPCNonceOracle(self.accounts[0], self.rpc)
c = DemurrageToken(self.chain_spec, signer=self.signer, nonce_oracle=nonce_oracle)
(tx_hash, o) = c.approve(self.address, self.accounts[0], self.accounts[1], int.from_bytes(b'\xff' * 32, byteorder='big'))
self.rpc.do(o)
o = receipt(tx_hash)
r = self.rpc.do(o)
self.assertEqual(r['status'], 1)
(tx_hash, o) = c.approve(self.address, self.accounts[0], self.accounts[1], 0)
self.rpc.do(o)
o = receipt(tx_hash)
r = self.rpc.do(o)
self.assertEqual(r['status'], 1)
self.backend.time_travel(self.start_time + (60 * 60 * 24 * 365 * 10))
c = DemurrageToken(self.chain_spec, signer=self.signer, nonce_oracle=nonce_oracle)
(tx_hash, o) = c.approve(self.address, self.accounts[0], self.accounts[1], int.from_bytes(b'\xff' * 32, byteorder='big'))
self.rpc.do(o)
o = receipt(tx_hash)
r = self.rpc.do(o)
self.assertEqual(r['status'], 1)
def test_transfer_from(self): def test_transfer_from(self):
nonce_oracle = RPCNonceOracle(self.accounts[0], self.rpc) nonce_oracle = RPCNonceOracle(self.accounts[0], self.rpc)
c = DemurrageToken(self.chain_spec, signer=self.signer, nonce_oracle=nonce_oracle) c = DemurrageToken(self.chain_spec, signer=self.signer, nonce_oracle=nonce_oracle)

View File

@ -1,314 +0,0 @@
# standard imports
import os
import unittest
import json
import logging
import datetime
# external imports
from chainlib.eth.constant import ZERO_ADDRESS
from chainlib.eth.nonce import RPCNonceOracle
from chainlib.eth.tx import receipt
from chainlib.eth.block import (
block_latest,
block_by_number,
)
# local imports
from erc20_demurrage_token import DemurrageToken
# test imports
from erc20_demurrage_token.unittest.base import TestDemurrageDefault
logging.basicConfig(level=logging.INFO)
logg = logging.getLogger()
testdir = os.path.dirname(__file__)
#TAX_LEVEL = 2
class TestBurn(TestDemurrageDefault):
def setUp(self):
super(TestBurn, self).setUp()
#
# def publish(self, tax_level=None):
# nonce_oracle = RPCNonceOracle(self.accounts[0], self.rpc)
# c = DemurrageToken(self.chain_spec, signer=self.signer, nonce_oracle=nonce_oracle)
#
# if tax_level != None:
# self.publisher.settings.demurrage_level = tax_level * (10 ** 32)
# self.publisher.settings.sink_address = self.accounts[9]
# self.publisher.sink_address = self.accounts[9]
# super(TestBurn, self).publish(c)
# Burn tokens and immediately check balances and supply
def test_burn_basic(self):
nonce_oracle = RPCNonceOracle(self.accounts[0], self.rpc)
c = DemurrageToken(self.chain_spec, signer=self.signer, nonce_oracle=nonce_oracle)
(tx_hash, o) = c.mint_to(self.address, self.accounts[0], self.accounts[1], 1000000)
r = self.rpc.do(o)
nonce_oracle = RPCNonceOracle(self.accounts[1], self.rpc)
c = DemurrageToken(self.chain_spec, signer=self.signer, nonce_oracle=nonce_oracle)
(tx_hash, o) = c.burn(self.address, self.accounts[1], 600000)
r = self.rpc.do(o)
o = receipt(tx_hash)
r = self.rpc.do(o)
self.assertEqual(r['status'], 0)
nonce_oracle = RPCNonceOracle(self.accounts[0], self.rpc)
c = DemurrageToken(self.chain_spec, signer=self.signer, nonce_oracle=nonce_oracle)
(tx_hash, o) = c.add_minter(self.address, self.accounts[0], self.accounts[1])
r = self.rpc.do(o)
nonce_oracle = RPCNonceOracle(self.accounts[1], self.rpc)
c = DemurrageToken(self.chain_spec, signer=self.signer, nonce_oracle=nonce_oracle)
(tx_hash, o) = c.burn(self.address, self.accounts[1], 600000)
r = self.rpc.do(o)
o = receipt(tx_hash)
r = self.rpc.do(o)
self.assertEqual(r['status'], 1)
o = c.total_supply(self.address, sender_address=self.accounts[0])
r = self.rpc.do(o)
new_supply = c.parse_total_supply(r)
self.assertEqual(new_supply, 400000)
o = c.total_burned(self.address, sender_address=self.accounts[0])
r = self.rpc.do(o)
burned = c.parse_total_burned(r)
self.assertEqual(burned, 600000)
# burn tokens and check sink balance and supply after first redistribution period
def test_burned_redistribution(self):
nonce_oracle = RPCNonceOracle(self.accounts[0], self.rpc)
c = DemurrageToken(self.chain_spec, signer=self.signer, nonce_oracle=nonce_oracle)
(tx_hash, o) = c.mint_to(self.address, self.accounts[0], self.accounts[0], 1000000000)
r = self.rpc.do(o)
(tx_hash, o) = c.burn(self.address, self.accounts[0], 500000000)
self.rpc.do(o)
(tx_hash, o) = c.transfer(self.address, self.accounts[0], self.sink_address, 500000000)
r = self.rpc.do(o)
self.backend.time_travel(self.start_time + self.period_seconds)
o = c.balance(self.address, self.sink_address, sender_address=self.accounts[0])
r = self.rpc.do(o)
bal = c.parse_balance(r)
self.assert_within(bal, 490000000, 1) # 2% == 10000000
(tx_hash, o) = c.change_period(self.address, self.accounts[0])
r = self.rpc.do(o)
o = receipt(tx_hash)
r = self.rpc.do(o)
self.assertEqual(r['status'], 1)
o = c.total_supply(self.address, sender_address=self.accounts[0])
r = self.rpc.do(o)
new_supply = c.parse_total_supply(r)
self.assertEqual(new_supply, 500000000)
o = c.balance(self.address, self.sink_address, sender_address=self.accounts[0])
r = self.rpc.do(o)
bal = c.parse_balance(r)
self.assert_within(bal, 500000000, 1)
self.backend.time_travel(self.start_time + (self.period_seconds * 2))
(tx_hash, o) = c.change_period(self.address, self.accounts[0])
r = self.rpc.do(o)
o = receipt(tx_hash)
r = self.rpc.do(o)
self.assertEqual(r['status'], 1)
o = c.total_supply(self.address, sender_address=self.accounts[0])
r = self.rpc.do(o)
new_supply = c.parse_total_supply(r)
self.assertEqual(new_supply, 500000000)
# if we don't burn anything more it should be the same
o = c.balance(self.address, self.sink_address, sender_address=self.accounts[0])
r = self.rpc.do(o)
bal = c.parse_balance(r)
self.assert_within_lower(bal, 500000000, 1)
# burn tokens and check sink and taxed balance and supply after first redistribution period
def test_burned_other_redistribution(self):
nonce_oracle = RPCNonceOracle(self.accounts[0], self.rpc)
c = DemurrageToken(self.chain_spec, signer=self.signer, nonce_oracle=nonce_oracle)
(tx_hash, o) = c.mint_to(self.address, self.accounts[0], self.accounts[0], 1000000000)
r = self.rpc.do(o)
(tx_hash, o) = c.burn(self.address, self.accounts[0], 500000000)
r = self.rpc.do(o)
(tx_hash, o) = c.transfer(self.address, self.accounts[0], self.accounts[1], 500000000)
r = self.rpc.do(o)
self.backend.time_travel(self.start_time + self.period_seconds)
o = c.balance(self.address, self.accounts[1], sender_address=self.accounts[0])
r = self.rpc.do(o)
bal = c.parse_balance(r)
#self.assertEqual(bal, 416873881) # 9 periods demurrage
self.assert_within(bal, 490000000, 1)
(tx_hash, o) = c.change_period(self.address, self.accounts[0])
r = self.rpc.do(o)
o = receipt(tx_hash)
r = self.rpc.do(o)
self.assertEqual(r['status'], 1)
o = c.total_supply(self.address, sender_address=self.accounts[0])
r = self.rpc.do(o)
new_supply = c.parse_total_supply(r)
self.assertEqual(new_supply, 500000000)
o = c.balance(self.address, self.accounts[1], sender_address=self.accounts[0])
r = self.rpc.do(o)
bal = c.parse_balance(r)
self.assert_within(bal, 490000000, 1)
o = c.balance(self.address, self.sink_address, sender_address=self.accounts[0])
r = self.rpc.do(o)
sink_bal = c.parse_balance(r)
self.assert_within_lower(sink_bal, 10000000, 1) # TODO is this ok variance, 1.0 is ppm?
self.backend.time_travel(self.start_time + (self.period_seconds * 2))
(tx_hash, o) = c.change_period(self.address, self.accounts[0])
r = self.rpc.do(o)
o = receipt(tx_hash)
r = self.rpc.do(o)
self.assertEqual(r['status'], 1)
o = c.total_supply(self.address, sender_address=self.accounts[0])
r = self.rpc.do(o)
new_supply = c.parse_total_supply(r)
self.assertEqual(new_supply, 500000000)
o = c.balance(self.address, self.accounts[1], sender_address=self.accounts[0])
r = self.rpc.do(o)
next_bal = c.parse_balance(r)
self.assert_within(next_bal, 480200000, 0.01)
o = c.balance(self.address, self.sink_address, sender_address=self.accounts[0])
r = self.rpc.do(o)
prev_sink_bal = sink_bal
bal = prev_sink_bal + (bal - next_bal)
sink_bal = c.parse_balance(r)
self.assert_within_lower(sink_bal, bal, 0.09) # TODO is this ok variance, 1.0 is ppm?
# verify expected results of balance and supply after multiple redistribution periods
def test_burn_accumulate(self):
nonce_oracle = RPCNonceOracle(self.accounts[0], self.rpc)
c = DemurrageToken(self.chain_spec, signer=self.signer, nonce_oracle=nonce_oracle)
(tx_hash, o) = c.add_minter(self.address, self.accounts[0], self.sink_address)
self.rpc.do(o)
o = receipt(tx_hash)
r = self.rpc.do(o)
self.assertEqual(r['status'], 1)
(tx_hash, o) = c.mint_to(self.address, self.accounts[0], self.sink_address, self.default_supply)
r = self.rpc.do(o)
balance_share = int(self.default_supply / 2)
nonce_oracle = RPCNonceOracle(self.sink_address, self.rpc)
c = DemurrageToken(self.chain_spec, signer=self.signer, nonce_oracle=nonce_oracle)
(tx_hash, o) = c.transfer(self.address, self.sink_address, self.accounts[1], balance_share)
r = self.rpc.do(o)
new_supply = None
burn_rate = 1000
sink_bal = None
bob_bal = None
bob_refund = None
o = c.balance(self.address, self.accounts[1], sender_address=self.accounts[0])
r = self.rpc.do(o)
bob_bal = c.parse_balance(r)
prev_bob_bal = bob_bal
o = c.balance(self.address, self.sink_address, sender_address=self.accounts[0])
r = self.rpc.do(o)
logg.info('sink has balance {}'.format(c.parse_balance(r)))
iterations = 100
for i in range(1, iterations + 1):
nonce_oracle = RPCNonceOracle(self.sink_address, self.rpc)
c = DemurrageToken(self.chain_spec, signer=self.signer, nonce_oracle=nonce_oracle)
if bob_refund != None:
(tx_hash, o) = c.transfer(self.address, self.sink_address, self.accounts[1], bob_refund)
r = self.rpc.do(o)
o = receipt(tx_hash)
r = self.rpc.do(o)
self.assertEqual(r['status'], 1)
(tx_hash, o) = c.burn(self.address, self.sink_address, burn_rate)
r = self.rpc.do(o)
o = receipt(tx_hash)
r = self.rpc.do(o)
self.assertEqual(r['status'], 1)
nonce_oracle = RPCNonceOracle(self.accounts[0], self.rpc)
c = DemurrageToken(self.chain_spec, signer=self.signer, nonce_oracle=nonce_oracle)
o = c.total_supply(self.address, sender_address=self.accounts[0])
r = self.rpc.do(o)
new_supply = c.parse_total_supply(r)
self.backend.time_travel(self.start_time + (self.period_seconds * i))
(tx_hash, o) = c.change_period(self.address, self.accounts[0])
self.rpc.do(o)
o = c.balance(self.address, self.accounts[1], sender_address=self.accounts[0])
r = self.rpc.do(o)
bob_bal = c.parse_balance(r)
bob_refund = prev_bob_bal - bob_bal
o = c.balance(self.address, self.sink_address, sender_address=self.accounts[0])
r = self.rpc.do(o)
burner_bal = c.parse_balance(r)
sum_supply = bob_bal + burner_bal
o = c.total_burned(self.address, sender_address=self.accounts[0])
r = self.rpc.do(o)
total_burned = c.parse_balance(r)
o = c.to_base_amount(self.address, total_burned, sender_address=self.accounts[0])
r = self.rpc.do(o)
total_burned_base = c.parse_balance(r)
expected_supply = self.default_supply - (burn_rate * i)
logg.info('checking burn round {} balance burner {} bob {} supply {} expected {} summed {} burned {} base {}'.format(i, burner_bal, bob_bal, new_supply, expected_supply, sum_supply, total_burned, total_burned_base))
self.assertEqual(new_supply, expected_supply)
sum_supply = burner_bal + bob_bal
logg.debug('balances sink {} bob {} total {} supply real {} original {}'.format(sink_bal, bob_bal, sum_supply, new_supply, self.default_supply))
self.assert_within_lower(sum_supply, new_supply, 1)
self.assert_within_lower(burner_bal, balance_share - total_burned + bob_refund, 1)
bob_delta = self.default_supply * ((2 / 1000000) / 1000)
self.assert_within_greater(bob_bal, balance_share - bob_delta - bob_refund, 1)
self.assertEqual(total_burned, iterations * burn_rate)
if __name__ == '__main__':
unittest.main()

View File

@ -1,114 +0,0 @@
# standard imports
import datetime
import unittest
import logging
import os
# external imports
from chainlib.eth.nonce import RPCNonceOracle
from chainlib.eth.tx import receipt
# local imports
from erc20_demurrage_token import DemurrageToken
from erc20_demurrage_token.demurrage import DemurrageCalculator
# test imports
from erc20_demurrage_token.unittest import TestDemurrageDefault
logging.basicConfig(level=logging.INFO)
logg = logging.getLogger()
class TestDemurragePeriods(TestDemurrageDefault):
# verify that tax level calculation is in ppm as expected
def test_ppm(self):
nonce_oracle = RPCNonceOracle(self.accounts[0], self.rpc)
c = DemurrageToken(self.chain_spec, signer=self.signer, nonce_oracle=nonce_oracle)
(tx_hash, o) = c.mint_to(self.address, self.accounts[0], self.accounts[1], self.default_supply)
r = self.rpc.do(o)
self.backend.time_travel(self.start_time + 60)
(tx_hash, o) = c.apply_demurrage(self.address, self.accounts[0])
self.rpc.do(o)
o = receipt(tx_hash)
r = self.rpc.do(o)
self.assertEqual(r['status'], 1)
o = c.balance(self.address, self.accounts[1], sender_address=self.accounts[0])
r = self.rpc.do(o)
bob_bal = c.parse_balance(r)
o = c.balance(self.address, self.sink_address, sender_address=self.accounts[0])
r = self.rpc.do(o)
sink_bal = c.parse_balance(r)
o = c.total_supply(self.address, sender_address=self.accounts[0])
r = self.rpc.do(o)
new_supply = c.parse_total_supply(r)
balance_delta = self.default_supply * ((2 / 1000000) / 1000)
self.assertEqual(bob_bal, self.default_supply - balance_delta)
# verify balances and supply after multiple demurrage periods
def test_over_time(self):
nonce_oracle = RPCNonceOracle(self.accounts[0], self.rpc)
c = DemurrageToken(self.chain_spec, signer=self.signer, nonce_oracle=nonce_oracle)
(tx_hash, o) = c.mint_to(self.address, self.accounts[0], self.accounts[1], self.default_supply)
r = self.rpc.do(o)
o = c.balance(self.address, self.accounts[1], sender_address=self.accounts[0])
r = self.rpc.do(o)
bob_bal = c.parse_balance(r)
prev_bob_bal = bob_bal
nonce_oracle = RPCNonceOracle(self.sink_address, self.rpc)
c = DemurrageToken(self.chain_spec, signer=self.signer, nonce_oracle=nonce_oracle)
iterations = 100
for i in range(1, iterations + 1):
self.backend.time_travel(self.start_time + (self.period_seconds * i))
(tx_hash, o) = c.transfer(self.address, self.sink_address, self.accounts[1], prev_bob_bal - bob_bal)
r = self.rpc.do(o)
o = receipt(tx_hash)
r = self.rpc.do(o)
self.assertEqual(r['status'], 1)
(tx_hash, o) = c.apply_demurrage(self.address, self.sink_address)
self.rpc.do(o)
o = receipt(tx_hash)
r = self.rpc.do(o)
self.assertEqual(r['status'], 1)
o = c.balance(self.address, self.accounts[1], sender_address=self.accounts[0])
r = self.rpc.do(o)
bob_bal = c.parse_balance(r)
o = c.balance(self.address, self.sink_address, sender_address=self.accounts[0])
r = self.rpc.do(o)
sink_bal = c.parse_balance(r)
o = c.total_supply(self.address, sender_address=self.accounts[0])
r = self.rpc.do(o)
new_supply = c.parse_total_supply(r)
logg.info('round {} supply {} balance sink {} bob {}'.format(i, new_supply, sink_bal, bob_bal))
sum_supply = sink_bal + bob_bal
bob_delta = self.default_supply * ((2 / 1000000) / 100)
self.assert_within_lower(sum_supply, new_supply, 0.00001)
self.assert_within_greater(bob_bal, self.default_supply - bob_delta, 0.001)
self.assert_within_lower(sink_bal, bob_delta, 1000)
if __name__ == '__main__':
unittest.main()

View File

@ -1,77 +0,0 @@
# standard imports
import os
import unittest
import json
import logging
# external imports
from chainlib.eth.constant import ZERO_ADDRESS
from chainlib.eth.nonce import RPCNonceOracle
from chainlib.eth.tx import receipt
from chainlib.eth.block import block_latest
from chainlib.eth.block import block_by_number
# local imports
from erc20_demurrage_token import DemurrageToken
# test imports
from erc20_demurrage_token.unittest import TestDemurrageDefault
logging.basicConfig(level=logging.DEBUG)
logg = logging.getLogger()
testdir = os.path.dirname(__file__)
class TestAmounts(TestDemurrageDefault):
def test_mint(self):
o = block_latest()
r = self.rpc.do(o)
o = block_by_number(r)
r = self.rpc.do(o)
tb = r['timestamp']
self.backend.time_travel(self.start_time + 800)
o = block_latest()
r = self.rpc.do(o)
o = block_by_number(r)
r = self.rpc.do(o)
ta = r['timestamp']
nonce_oracle = RPCNonceOracle(self.accounts[0], self.rpc)
c = DemurrageToken(self.chain_spec, signer=self.signer, nonce_oracle=nonce_oracle)
(tx_hash, o) = c.mint_to(self.address, self.accounts[0], self.accounts[1], 1000)
r = self.rpc.do(o)
o = receipt(tx_hash)
r = self.rpc.do(o)
self.assertEqual(r['status'], 1)
def test_writer(self):
nonce_oracle = RPCNonceOracle(self.accounts[1], self.rpc)
c = DemurrageToken(self.chain_spec, signer=self.signer, nonce_oracle=nonce_oracle)
(tx_hash, o) = c.mint_to(self.address, self.accounts[1], self.accounts[1], 1000)
r = self.rpc.do(o)
o = receipt(tx_hash)
r = self.rpc.do(o)
self.assertEqual(r['status'], 0)
nonce_oracle = RPCNonceOracle(self.accounts[0], self.rpc)
c = DemurrageToken(self.chain_spec, signer=self.signer, nonce_oracle=nonce_oracle)
(tx_hash, o) = c.add_writer(self.address, self.accounts[0], self.accounts[1])
r = self.rpc.do(o)
o = receipt(tx_hash)
r = self.rpc.do(o)
self.assertEqual(r['status'], 1)
nonce_oracle = RPCNonceOracle(self.accounts[1], self.rpc)
c = DemurrageToken(self.chain_spec, signer=self.signer, nonce_oracle=nonce_oracle)
(tx_hash, o) = c.mint_to(self.address, self.accounts[1], self.accounts[1], 1000)
r = self.rpc.do(o)
o = receipt(tx_hash)
r = self.rpc.do(o)
self.assertEqual(r['status'], 1)
if __name__ == '__main__':
unittest.main()

View File

@ -34,7 +34,6 @@ testdir = os.path.dirname(__file__)
class TestRedistribution(TestDemurrageDefault): class TestRedistribution(TestDemurrageDefault):
# TODO: move to "pure" test file when getdistribution is implemented in all contracts # TODO: move to "pure" test file when getdistribution is implemented in all contracts
def test_distribution_direct(self): def test_distribution_direct(self):
nonce_oracle = RPCNonceOracle(self.accounts[0], self.rpc) nonce_oracle = RPCNonceOracle(self.accounts[0], self.rpc)

View File

@ -1,19 +1,17 @@
pragma solidity >= 0.8.0; pragma solidity >= 0.8.0;
import "aux/ABDKMath64x64.sol"; import "aux/ABDKMath64x64.sol";
// SPDX-License-Identifier: AGPL-3.0-or-later // SPDX-License-Identifier: GPL-3.0-or-later
contract DemurrageTokenSingleNocap { contract DemurrageTokenSingleNocap {
uint256 constant VALUE_LIMIT = 1 << 63;
struct redistributionItem { struct redistributionItem {
uint32 period; uint32 period;
uint72 value; uint72 value;
uint64 demurrage; uint64 demurrage;
} }
redistributionItem[] public redistributions; redistributionItem[] public redistributions; // uint51(unused) | uint64(demurrageModifier) | uint36(participants) | uint72(value) | uint32(period)
// Account balances // Account balances
mapping (address => uint256) account; mapping (address => uint256) account;
@ -25,7 +23,7 @@ contract DemurrageTokenSingleNocap {
// Cached demurrage timestamp; the timestamp for which demurrageAmount was last calculated // Cached demurrage timestamp; the timestamp for which demurrageAmount was last calculated
uint256 public demurrageTimestamp; uint256 public demurrageTimestamp;
// Implements EIP173 // Implements EIP172
address public owner; address public owner;
address newOwner; address newOwner;
@ -39,6 +37,8 @@ contract DemurrageTokenSingleNocap {
// Implements ERC20 // Implements ERC20
uint256 public immutable decimals; uint256 public immutable decimals;
// Implements ERC20
//uint256 public totalSupply;
uint256 supply; uint256 supply;
// Last executed period // Last executed period
@ -48,7 +48,7 @@ contract DemurrageTokenSingleNocap {
uint256 public totalSink; uint256 public totalSink;
// Value of burnt tokens (burnt tokens do not decay) // Value of burnt tokens (burnt tokens do not decay)
uint256 burned; uint256 public burned;
// 128 bit resolution of the demurrage divisor // 128 bit resolution of the demurrage divisor
// (this constant x 1000000 is contained within 128 bits) // (this constant x 1000000 is contained within 128 bits)
@ -67,15 +67,15 @@ contract DemurrageTokenSingleNocap {
uint256 public immutable periodDuration; uint256 public immutable periodDuration;
// Demurrage in ppm per minute // Demurrage in ppm per minute
//uint256 public immutable decayLevel; //uint256 public immutable taxLevel;
// 64x64 // 64x64
int128 public immutable decayLevel; int128 public immutable taxLevel;
// Addresses allowed to mint new tokens // Addresses allowed to mint new tokens
mapping (address => bool) minter; mapping (address => bool) minter;
// Storage for ERC20 approve/transferFrom methods // Storage for ERC20 approve/transferFrom methods
mapping (address => mapping (address => uint256 ) ) public allowance; // holder -> spender -> amount (amount is subject to demurrage) mapping (address => mapping (address => uint256 ) ) allowance; // holder -> spender -> amount (amount is subject to demurrage)
// Address to send unallocated redistribution tokens // Address to send unallocated redistribution tokens
address public sinkAddress; address public sinkAddress;
@ -93,7 +93,7 @@ contract DemurrageTokenSingleNocap {
// Implements ERC20 // Implements ERC20
event Approval(address indexed _owner, address indexed _spender, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value);
// Implements Minter // New tokens minted
event Mint(address indexed _minter, address indexed _beneficiary, uint256 _value); event Mint(address indexed _minter, address indexed _beneficiary, uint256 _value);
// New demurrage cache milestone calculated // New demurrage cache milestone calculated
@ -109,38 +109,32 @@ contract DemurrageTokenSingleNocap {
//event Debug(bytes32 _foo); //event Debug(bytes32 _foo);
event Debug(int128 indexed _foo, uint256 indexed _bar); event Debug(int128 indexed _foo, uint256 indexed _bar);
// Implements Burn // Emitted when tokens are burned
event Burn(address indexed _burner, uint256 _value); event Burn(address indexed _burner, uint256 _value);
// EIP173 // EIP173
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); // EIP173 event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); // EIP173
// Implements Expire event SealStateChange(uint256 _sealState);
event Expired(uint256 _timestamp);
// Implements Expire event Expired(uint256 _timestamp);
event ExpiryChange(uint256 indexed _oldTimestamp, uint256 _newTimestamp);
event Cap(uint256 indexed _oldCap, uint256 _newCap); event Cap(uint256 indexed _oldCap, uint256 _newCap);
// Implements Seal // property sealing
uint256 public sealState; uint256 public sealState;
uint8 constant WRITER_STATE = 1; uint8 constant MINTER_STATE = 1;
uint8 constant SINK_STATE = 2; uint8 constant SINK_STATE = 2;
uint8 constant EXPIRY_STATE = 4; uint8 constant EXPIRY_STATE = 4;
uint8 constant CAP_STATE = 8; uint8 constant CAP_STATE = 8;
// Implements Seal
uint256 constant public maxSealState = 15; uint256 constant public maxSealState = 15;
// Implements Seal
event SealStateChange(bool indexed _final, uint256 _sealState);
constructor(string memory _name, string memory _symbol, uint8 _decimals, int128 _taxLevel, uint256 _periodMinutes, address _defaultSinkAddress) {
constructor(string memory _name, string memory _symbol, uint8 _decimals, int128 _decayLevel, uint256 _periodMinutes, address _defaultSinkAddress) { require(_taxLevel < (1 << 64));
require(_decayLevel < (1 << 64));
redistributionItem memory initialRedistribution; redistributionItem memory initialRedistribution;
//require(ABDKMath64x64.toUInt(_decayLevel) == 0); //require(ABDKMath64x64.toUInt(_taxLevel) == 0);
// ACL setup // ACL setup
owner = msg.sender; owner = msg.sender;
@ -156,7 +150,7 @@ contract DemurrageTokenSingleNocap {
periodDuration = _periodMinutes * 60; periodDuration = _periodMinutes * 60;
demurrageAmount = ABDKMath64x64.fromUInt(1); demurrageAmount = ABDKMath64x64.fromUInt(1);
decayLevel = ABDKMath64x64.ln(_decayLevel); taxLevel = ABDKMath64x64.ln(_taxLevel);
initialRedistribution = toRedistribution(0, demurrageAmount, 0, 1); initialRedistribution = toRedistribution(0, demurrageAmount, 0, 1);
redistributions.push(initialRedistribution); redistributions.push(initialRedistribution);
@ -168,11 +162,11 @@ contract DemurrageTokenSingleNocap {
require(_state < 16, 'ERR_INVALID_STATE'); require(_state < 16, 'ERR_INVALID_STATE');
require(_state & sealState == 0, 'ERR_ALREADY_LOCKED'); require(_state & sealState == 0, 'ERR_ALREADY_LOCKED');
sealState |= _state; sealState |= _state;
emit SealStateChange(sealState == maxSealState, sealState); emit SealStateChange(sealState);
return uint256(sealState); return uint256(sealState);
} }
function isSealed(uint256 _state) public view returns(bool) { function isSealed(uint256 _state) public returns(bool) {
require(_state < maxSealState); require(_state < maxSealState);
if (_state == 0) { if (_state == 0) {
return sealState == maxSealState; return sealState == maxSealState;
@ -180,25 +174,17 @@ contract DemurrageTokenSingleNocap {
return _state & sealState == _state; return _state & sealState == _state;
} }
// Set when token expires.
// Value is set it terms of redistribution periods.
// Cannot be set to a time in the past.
function setExpirePeriod(uint256 _expirePeriod) public { function setExpirePeriod(uint256 _expirePeriod) public {
uint256 r; uint256 r;
uint256 oldTimestamp;
require(!isSealed(EXPIRY_STATE)); require(!isSealed(EXPIRY_STATE));
require(!expired); require(!expired);
require(msg.sender == owner); require(msg.sender == owner);
r = periodStart + (_expirePeriod * periodDuration); r = periodStart + (_expirePeriod * periodDuration);
require(r > expires); require(r > expires);
oldTimestamp = expires;
expires = r; expires = r;
emit ExpiryChange(oldTimestamp, expires);
} }
// Change max token supply.
// Can only increase supply cap, not decrease.
function setMaxSupply(uint256 _cap) public { function setMaxSupply(uint256 _cap) public {
require(!isSealed(CAP_STATE)); require(!isSealed(CAP_STATE));
require(msg.sender == owner); require(msg.sender == owner);
@ -217,7 +203,6 @@ contract DemurrageTokenSingleNocap {
// Expire the contract if expire is set and we have gone over the threshold. // Expire the contract if expire is set and we have gone over the threshold.
// Finalizes demurrage up to the timestamp of the expiry. // Finalizes demurrage up to the timestamp of the expiry.
// The first approve, transfer or transferFrom call that hits the ex == 2 will get the tx mined. but without the actual effect. Otherwise we would have to wait until an external egent called applyExpiry to get the correct final balance. // The first approve, transfer or transferFrom call that hits the ex == 2 will get the tx mined. but without the actual effect. Otherwise we would have to wait until an external egent called applyExpiry to get the correct final balance.
// Implements Expire
function applyExpiry() public returns(uint8) { function applyExpiry() public returns(uint8) {
if (expired) { if (expired) {
return 1; return 1;
@ -236,33 +221,27 @@ contract DemurrageTokenSingleNocap {
} }
// Given address will be allowed to call the mintTo() function // Given address will be allowed to call the mintTo() function
// Implements Writer
function addWriter(address _minter) public returns (bool) { function addWriter(address _minter) public returns (bool) {
require(!isSealed(WRITER_STATE)); require(!isSealed(MINTER_STATE));
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
// Implements Writer
function deleteWriter(address _minter) public returns (bool) { function deleteWriter(address _minter) public returns (bool) {
require(!isSealed(WRITER_STATE)); require(!isSealed(MINTER_STATE));
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 Writer
function isWriter(address _minter) public view returns(bool) {
return minter[_minter] || _minter == owner;
}
/// Implements ERC20 /// Implements ERC20
function balanceOf(address _account) public view returns (uint256) { function balanceOf(address _account) public view returns (uint256) {
int128 baseBalance; int128 baseBalance;
int128 currentDemurragedAmount; int128 currentDemurragedAmount;
uint256 periodCount; uint256 periodCount;
uint8 expiryState;
baseBalance = ABDKMath64x64.fromUInt(baseBalanceOf(_account)); baseBalance = ABDKMath64x64.fromUInt(baseBalanceOf(_account));
@ -280,6 +259,7 @@ contract DemurrageTokenSingleNocap {
/// Increases base balance for a single account /// Increases base balance for a single account
function increaseBaseBalance(address _account, uint256 _delta) private returns (bool) { function increaseBaseBalance(address _account, uint256 _delta) private returns (bool) {
uint256 oldBalance; uint256 oldBalance;
uint256 newBalance;
uint256 workAccount; uint256 workAccount;
workAccount = uint256(account[_account]); workAccount = uint256(account[_account]);
@ -296,6 +276,7 @@ contract DemurrageTokenSingleNocap {
/// Decreases base balance for a single account /// Decreases base balance for a single account
function decreaseBaseBalance(address _account, uint256 _delta) private returns (bool) { function decreaseBaseBalance(address _account, uint256 _delta) private returns (bool) {
uint256 oldBalance; uint256 oldBalance;
uint256 newBalance;
uint256 workAccount; uint256 workAccount;
workAccount = uint256(account[_account]); workAccount = uint256(account[_account]);
@ -310,25 +291,13 @@ contract DemurrageTokenSingleNocap {
return true; return true;
} }
// Send full balance of one account to another
function sweep(address _account) public returns (uint256) {
uint256 v;
v = account[msg.sender];
account[msg.sender] = 0;
account[_account] += v;
emit Transfer(msg.sender, _account, v);
return v;
}
// Creates new tokens out of thin air, and allocates them to the given address // Creates new tokens out of thin air, and allocates them to the given address
// Triggers tax // Triggers tax
// Implements Minter function mintTo(address _beneficiary, uint256 _amount) external returns (bool) {
function mintTo(address _beneficiary, uint256 _amount) public returns (bool) {
uint256 baseAmount; uint256 baseAmount;
require(applyExpiry() == 0); require(applyExpiry() == 0);
require(minter[msg.sender] || msg.sender == owner, 'ERR_ACCESS'); require(minter[msg.sender], 'ERR_ACCESS');
changePeriod(); changePeriod();
if (maxSupply > 0) { if (maxSupply > 0) {
@ -343,18 +312,6 @@ contract DemurrageTokenSingleNocap {
return true; return true;
} }
// Implements Minter
function mint(address _beneficiary, uint256 _amount, bytes calldata _data) public {
_data;
mintTo(_beneficiary, _amount);
}
// Implements Minter
function safeMint(address _beneficiary, uint256 _amount, bytes calldata _data) public {
_data;
mintTo(_beneficiary, _amount);
}
// Deserializes the redistribution word // Deserializes the redistribution word
function toRedistribution(uint256 _participants, int128 _demurrageModifier, uint256 _value, uint256 _period) public pure returns(redistributionItem memory) { function toRedistribution(uint256 _participants, int128 _demurrageModifier, uint256 _value, uint256 _period) public pure returns(redistributionItem memory) {
redistributionItem memory redistribution; redistributionItem memory redistribution;
@ -362,7 +319,6 @@ contract DemurrageTokenSingleNocap {
redistribution.period = uint32(_period); redistribution.period = uint32(_period);
redistribution.value = uint72(_value); redistribution.value = uint72(_value);
redistribution.demurrage = uint64(uint128(_demurrageModifier) & 0xffffffffffffffff); redistribution.demurrage = uint64(uint128(_demurrageModifier) & 0xffffffffffffffff);
_participants;
return redistribution; return redistribution;
} }
@ -425,7 +381,7 @@ contract DemurrageTokenSingleNocap {
return lastRedistribution; return lastRedistribution;
} }
function getDistribution(uint256 _supply, int128 _demurrageAmount) public pure returns (uint256) { function getDistribution(uint256 _supply, int128 _demurrageAmount) public view returns (uint256) {
int128 difference; int128 difference;
difference = ABDKMath64x64.mul(ABDKMath64x64.fromUInt(_supply), ABDKMath64x64.sub(ABDKMath64x64.fromUInt(1), _demurrageAmount)); difference = ABDKMath64x64.mul(ABDKMath64x64.fromUInt(_supply), ABDKMath64x64.sub(ABDKMath64x64.fromUInt(1), _demurrageAmount));
@ -433,7 +389,7 @@ contract DemurrageTokenSingleNocap {
} }
function getDistributionFromRedistribution(redistributionItem memory _redistribution) public pure returns (uint256) { function getDistributionFromRedistribution(redistributionItem memory _redistribution) public returns (uint256) {
uint256 redistributionSupply; uint256 redistributionSupply;
int128 redistributionDemurrage; int128 redistributionDemurrage;
@ -481,7 +437,7 @@ contract DemurrageTokenSingleNocap {
lastDemurrageAmount = toRedistributionDemurrageModifier(lastRedistribution); lastDemurrageAmount = toRedistributionDemurrageModifier(lastRedistribution);
demurrageCounts = (periodDuration * currentPeriod) / 60; demurrageCounts = (periodDuration * currentPeriod) / 60;
// TODO refactor decayby to take int128 then DRY with it // TODO refactor decayby to take int128 then DRY with it
nextRedistributionDemurrage = ABDKMath64x64.exp(ABDKMath64x64.mul(decayLevel, ABDKMath64x64.fromUInt(demurrageCounts))); nextRedistributionDemurrage = ABDKMath64x64.exp(ABDKMath64x64.mul(taxLevel, ABDKMath64x64.fromUInt(demurrageCounts)));
nextRedistribution = toRedistribution(0, nextRedistributionDemurrage, totalSupply(), nextPeriod); nextRedistribution = toRedistribution(0, nextRedistributionDemurrage, totalSupply(), nextPeriod);
redistributions.push(nextRedistribution); redistributions.push(nextRedistribution);
@ -524,7 +480,7 @@ contract DemurrageTokenSingleNocap {
} }
periodPoint = ABDKMath64x64.fromUInt(periodCount); periodPoint = ABDKMath64x64.fromUInt(periodCount);
v = ABDKMath64x64.mul(decayLevel, periodPoint); v = ABDKMath64x64.mul(taxLevel, periodPoint);
v = ABDKMath64x64.exp(v); v = ABDKMath64x64.exp(v);
demurrageAmount = ABDKMath64x64.mul(demurrageAmount, v); demurrageAmount = ABDKMath64x64.mul(demurrageAmount, v);
@ -543,7 +499,6 @@ contract DemurrageTokenSingleNocap {
return (block.timestamp - _target) / 60; return (block.timestamp - _target) / 60;
} }
// Equality check for empty redistribution data
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;
@ -567,7 +522,7 @@ contract DemurrageTokenSingleNocap {
valuePoint = ABDKMath64x64.fromUInt(_value); valuePoint = ABDKMath64x64.fromUInt(_value);
periodPoint = ABDKMath64x64.fromUInt(_period); periodPoint = ABDKMath64x64.fromUInt(_period);
v = ABDKMath64x64.mul(decayLevel, periodPoint); v = ABDKMath64x64.mul(taxLevel, periodPoint);
v = ABDKMath64x64.exp(v); v = ABDKMath64x64.exp(v);
v = ABDKMath64x64.mul(valuePoint, v); v = ABDKMath64x64.mul(valuePoint, v);
return ABDKMath64x64.toUInt(v); return ABDKMath64x64.toUInt(v);
@ -581,8 +536,7 @@ contract DemurrageTokenSingleNocap {
return ABDKMath64x64.toUInt(r); return ABDKMath64x64.toUInt(r);
} }
// Triggers tax and/or redistribution // Implements ERC20, triggers tax and/or redistribution
// Implements ERC20
function approve(address _spender, uint256 _value) public returns (bool) { function approve(address _spender, uint256 _value) public returns (bool) {
uint256 baseValue; uint256 baseValue;
uint8 ex; uint8 ex;
@ -599,14 +553,7 @@ contract DemurrageTokenSingleNocap {
changePeriod(); changePeriod();
// dex code will attempt uint256max approve, but contract cannot handle that size baseValue = toBaseAmount(_value);
// truncate to biggest possible value
if (_value <= VALUE_LIMIT) {
baseValue = toBaseAmount(_value);
} else {
baseValue = VALUE_LIMIT;
}
allowance[msg.sender][_spender] = baseValue; allowance[msg.sender][_spender] = baseValue;
emit Approval(msg.sender, _spender, _value); emit Approval(msg.sender, _spender, _value);
return true; return true;
@ -639,8 +586,7 @@ contract DemurrageTokenSingleNocap {
return true; return true;
} }
// Triggers tax and/or redistribution // Implements ERC20, triggers tax and/or redistribution
// Implements ERC20
function transfer(address _to, uint256 _value) public returns (bool) { function transfer(address _to, uint256 _value) public returns (bool) {
uint256 baseValue; uint256 baseValue;
bool result; bool result;
@ -660,8 +606,7 @@ contract DemurrageTokenSingleNocap {
return result; return result;
} }
// Triggers tax and/or redistribution // Implements ERC20, triggers tax and/or redistribution
// Implements ERC20
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
uint256 baseValue; uint256 baseValue;
bool result; bool result;
@ -687,6 +632,8 @@ contract DemurrageTokenSingleNocap {
// ERC20 transfer backend for transfer, transferFrom // ERC20 transfer backend for transfer, transferFrom
function transferBase(address _from, address _to, uint256 _value) private returns (bool) { function transferBase(address _from, address _to, uint256 _value) private returns (bool) {
uint256 period;
decreaseBaseBalance(_from, _value); decreaseBaseBalance(_from, _value);
increaseBaseBalance(_to, _value); increaseBaseBalance(_to, _value);
@ -695,22 +642,26 @@ contract DemurrageTokenSingleNocap {
// Implements EIP173 // Implements EIP173
function transferOwnership(address _newOwner) public returns (bool) { function transferOwnership(address _newOwner) public returns (bool) {
require(msg.sender == owner);
newOwner = _newOwner;
}
// Implements OwnedAccepter
function acceptOwnership() public returns (bool) {
address oldOwner; address oldOwner;
require(msg.sender == owner); require(msg.sender == newOwner);
oldOwner = owner; oldOwner = owner;
owner = _newOwner; owner = newOwner;
newOwner = address(0);
emit OwnershipTransferred(oldOwner, owner); emit OwnershipTransferred(oldOwner, owner);
return true;
} }
// Explicitly and irretrievably burn tokens // Explicitly and irretrievably burn tokens
// Only token minters can burn tokens // Only token minters can burn tokens
// Implements Burner function burn(uint256 _value) public {
function burn(uint256 _value) public returns(bool) {
require(applyExpiry() == 0); require(applyExpiry() == 0);
require(minter[msg.sender] || msg.sender == owner, 'ERR_ACCESS'); require(minter[msg.sender]);
require(_value <= account[msg.sender]); require(_value <= account[msg.sender]);
uint256 _delta = toBaseAmount(_value); uint256 _delta = toBaseAmount(_value);
@ -718,19 +669,6 @@ contract DemurrageTokenSingleNocap {
decreaseBaseBalance(msg.sender, _delta); decreaseBaseBalance(msg.sender, _delta);
burned += _value; burned += _value;
emit Burn(msg.sender, _value); emit Burn(msg.sender, _value);
return true;
}
// Implements Burner
function burn(address _from, uint256 _value, bytes calldata _data) public {
require(_from == msg.sender, 'ERR_ONLY_SELF_BURN');
_data;
burn(_value);
}
// Implements Burner
function burn() public returns(bool) {
return burn(account[msg.sender]);
} }
// Implements ERC20 // Implements ERC20
@ -739,45 +677,25 @@ contract DemurrageTokenSingleNocap {
} }
// Return total number of burned tokens // Return total number of burned tokens
// Implements Burner
function totalBurned() public view returns (uint256) { function totalBurned() public view returns (uint256) {
return burned; return burned;
} }
// Return total number of tokens ever minted
// Implements Burner
function totalMinted() public view returns (uint256) {
return supply;
}
// Implements EIP165 // Implements EIP165
function supportsInterface(bytes4 _sum) public pure returns (bool) { function supportsInterface(bytes4 _sum) public pure returns (bool) {
if (_sum == 0xb61bc941) { // ERC20 if (_sum == 0xc6bb4b70) { // ERC20
return true; return true;
} }
if (_sum == 0x5878bcf4) { // Minter if (_sum == 0x449a52f8) { // Minter
return true; return true;
} }
if (_sum == 0xbc4babdd) { // Burner if (_sum == 0x01ffc9a7) { // EIP165
return true; return true;
} }
if (_sum == 0x0d7491f8) { // Seal if (_sum == 0x9493f8b2) { // EIP173
return true; return true;
} }
if (_sum == 0xabe1f1f5) { // Writer if (_sum == 0x37a47be4) { // OwnedAccepter
return true;
}
if (_sum == 0x841a0e94) { // Expire
return true;
}
if (_sum == 0x01ffc9a7) { // ERC165
return true;
}
if (_sum == 0x9493f8b2) { // ERC173
return true;
}
if (_sum == 0xd0017968) { // ERC5678Ext20
return true; return true;
} }
return false; return false;

View File

@ -5,7 +5,6 @@ all: single_nocap
single_nocap: single_nocap:
$(SOLC) DemurrageTokenSingleNocap.sol --abi --evm-version byzantium | awk 'NR==4' > DemurrageTokenSingleNocap.json $(SOLC) DemurrageTokenSingleNocap.sol --abi --evm-version byzantium | awk 'NR==4' > DemurrageTokenSingleNocap.json
$(SOLC) DemurrageTokenSingleNocap.sol --bin --evm-version byzantium | awk 'NR==4' > DemurrageTokenSingleNocap.bin $(SOLC) DemurrageTokenSingleNocap.sol --bin --evm-version byzantium | awk 'NR==4' > DemurrageTokenSingleNocap.bin
$(SOLC) DemurrageTokenSingleNocap.sol --metadata --evm-version byzantium | awk 'NR==4' > DemurrageTokenSingleNocap.metadata.json
truncate -s -1 DemurrageTokenSingleNocap.bin truncate -s -1 DemurrageTokenSingleNocap.bin
single: single_nocap single: single_nocap