Compare commits

...

24 Commits

Author SHA1 Message Date
lash a40385a5a0
Truncate approve request out of value bounds 2023-10-05 17:41:52 +01:00
lash d7051b26c0
Make allowance method public 2023-09-05 03:22:33 +01:00
lash 14fb2fe8ea
Transfer event 2023-08-14 14:10:09 +01:00
lash 6d7792110d
Package man page with python 2023-05-18 06:42:14 +01:00
lash 76e8170014
Add makefiles, update readme 2023-05-16 11:21:38 +01:00
lash 091967bafd
WIP texinfo docs, elaborate on tools, supply cap 2023-05-15 15:22:59 +01:00
lash 0ed97b36b0
WIP texinfo documentation as improvement over existing readme 2023-05-14 21:07:11 +01:00
lash 8242d3a62f
Add ExpiryChange event 2023-03-26 08:03:44 +01:00
lash f2648dfb68
Update Expire ERC165 signature 2023-03-26 07:34:27 +01:00
lash d4906529a3
Update interfaces, add ERC5679 aliases 2023-03-26 07:26:02 +01:00
lash badfa4838a
Update license, upgrade to beta, update classifiers 2023-03-22 12:58:35 +00:00
lash 68c15082fb
Upgrade deps 2023-03-22 10:24:29 +00:00
lash acd5eb3d7b
Merge branch lash/readmemore 2023-03-22 10:18:51 +00:00
lash f052529935
Fix burn interface implementation 2023-03-22 07:58:25 +00:00
lash 1d93ece13e
Eliminate solidity compiler warnings 2023-03-19 09:23:51 +00:00
lash 50405b5cf6
Add expiration, supply cap, mutability to readme 2023-03-08 07:55:52 +00:00
lash 74c0bfe43e
Add solc metadata 2023-03-07 10:23:39 +00:00
lash 83383c0b9b
Recompile with solc 0.8.18+commit.87f61d96 2023-03-07 10:16:59 +00:00
lash 954630132b
Remove last edit line 2023-03-01 12:03:25 +00:00
lash f75472fcf5
Update readme for calculations and inputs 2023-03-01 12:01:32 +00:00
Mohamed Sohail 3ebb645077 Merge branch 'lash/safe-decay' into 'master'
Add burn method + minor bug fixes

See merge request cicnet/erc20-demurrage-token!12
2023-02-04 14:41:40 +00:00
Louis Holbrook 5d01e2ae96 Add burn method + minor bug fixes 2023-02-04 14:41:40 +00:00
Mohamed Sohail 99a9915d11 Merge branch 'dev-0.2.0' into 'master'
Runaway redistribution

See merge request cicnet/erc20-demurrage-token!10
2022-05-30 07:53:22 +00:00
Louis Holbrook 20e3a783fd Runaway redistribution 2022-05-30 07:53:22 +00:00
39 changed files with 2339 additions and 144 deletions

1
CAVEAT Normal file
View File

@ -0,0 +1 @@
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.

10
Makefile Normal file
View File

@ -0,0 +1,10 @@
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

446
README.md
View File

@ -1,95 +1,405 @@
# RedistributedDemurrageToken
# Overview
# RedistributedDemurrageToken
de-mur-rage
**Last edit: Will Ruddick Feburary 19 2023**
1: the detention of a ship by the freighter beyond the time allowed for loading, unloading, or sailing
## Use Case
* Vouchers
* A Publisher may publish a RedistributedDemurrageToken (Voucher) representing a credit obligation of an Issuer or Association of Issuers that can be redeemed as payment for the products of the Issuer. The Issuer is the entity legally obligated to redeem the voucher as payment.
* Decay: The Publisher can specify an decay rate such as 2% as well as a redistribution period. After the redistribution period such as a month. Assuming an account holder has not had any transfers they will have a new balance of their original balance*2%. Note that the numeric decay will happen continuously by the minute.
* Redistribution: The missing (demurraged) balances will be added to the balance of the SINK address. So once a redistribution period (e.g. once a month) the total supply of all holders including the SINK will return to the minted supply.
* This is meant to result as a disincentivization to hold (hodl) the Voucher without causing price inflation, as the total supply is stable.
* Example
- With a demurrage of 2% (and redistribution period of 1 month) - If there are 10 users all with balances of 100 Vouchers (and only 2 of them trade that month (assume they trade back and forth with no net balance change)).
- Then the resulting balances after one redistribution period of ALL users (regardless of their trading) would be 98 Vouchers and 20 Voucher would be the balance of the SINK address. Assuming the SINK address is redistributed (as a Community Fund) back to users, its balance would again reach 20 the next redistribution 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.
2: a charge for detaining a ship, freight car, or truck
This ERC20 smart contract implementation for the EVM imposes a demurrage
on all held token balances.
The demurrage is a continuous value *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.
## 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
* `Demurrage` aka Decay amount: A percentage of token supply that will gradually be removed over a redstribution period and then redistributed to the SINK account.
* 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`
A percentage of token supply that will continuously be removed.
`Demurrage Period`
A period of time denominated in minutes after which demurraged amounts
are available for redistribution.
## Ownership
`Sink Account`
The intermediate beneficiary of the demurraged amount, which may or may
not redistribute value.
* Contract creator is owner
* Ownership can be transferred
`Base balance`
The inflated balance of each used which is stored for bookkeeping.
# Use Case
## Mint
The use-case inspiring this implementation is in the context of issuance
of a *voucher* representing a credit obligation of an *Issuer* or
*Association of Issuers*.
* 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
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.
## Demurrage
* 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`
Introducing demurrage on this vehicle discourages *withholding* the
voucher, for example for speculative advantage.
This also encourages increased *velocity* of voucher use.
## Redistribution
## Example
* 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.
Given:
- 10 voucher holders.
## Data structures
- A total supply of 1000 tokens.
* 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
- Demurrage of 2% per 30 days (43200 minutes).
### Notes
- Redistribution period of 30 days (43200 minutes).
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.
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.
## QA
Note that after the redistribution the total of all balances will equal
the total minted amount.
* Basic python tests in place
* How to determine and generate sufficient test vectors, and how to adapt them to scripts.
* Audit sources?
Note that all accounts holding such vouchers are effected by demurrage
(even the Sink Account, pending redistribution).
## Known issues
# Smart contract
* A `transferFrom` following an `approve` call, when called across period thresholds, may fail if margin to demurraged amount is insufficient.
## 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.
### 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.

8
ROADMAP Normal file
View File

@ -0,0 +1,8 @@
- 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.

1
VERSION Normal file
View File

@ -0,0 +1 @@
0.2.0

4
doc/texinfo/Makefile Normal file
View File

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

221
doc/texinfo/contract.texi Normal file
View File

@ -0,0 +1,221 @@
@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.

29
doc/texinfo/index.texi Normal file
View File

@ -0,0 +1,29 @@
\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

47
doc/texinfo/overview.texi Normal file
View File

@ -0,0 +1,47 @@
@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

57
doc/texinfo/tools.texi Normal file
View File

@ -0,0 +1,57 @@
@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

32
doc/texinfo/usecase.texi Normal file
View File

@ -0,0 +1,32 @@
@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,3 +1,21 @@
- 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
@ -10,6 +28,12 @@
* Deployer script now takes demurrage amount as ppm instead of literal growth fraction
* Retire old multi and cap contracts
* 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
* Settable demurrage steps for apply demurrage cli tool
- 0.1.0

661
python/LICENSE Normal file
View File

@ -0,0 +1,661 @@
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
include erc20_demurrage_token/data/* erc20_demurrage_token/data/config/*.ini *requirements.txt man/build/*.1

8
python/Makefile Normal file
View File

@ -0,0 +1,8 @@
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

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

@ -101,7 +101,7 @@ class DemurrageToken(ERC20, SealedContract, ExpiryContract):
@staticmethod
def gas(code=None):
return 6000000
return 7000000
@staticmethod

View File

@ -61,10 +61,10 @@ class TestTokenDeploy:
self.start_time = int(r['timestamp'])
def deploy(self, rpc, deployer_address, interface, supply_cap=0):
def publish(self, rpc, publisher_address, interface, supply_cap=0):
tx_hash = None
o = None
(tx_hash, o) = interface.constructor(deployer_address, self.settings)
(tx_hash, o) = interface.constructor(publisher_address, self.settings)
r = rpc.do(o)
o = receipt(tx_hash)
@ -89,7 +89,7 @@ class TestDemurrage(EthTesterCase):
period = getattr(self, 'period')
except AttributeError as e:
pass
self.deployer = TestTokenDeploy(self.rpc, period=period, sink_address=self.accounts[9])
self.publisher = TestTokenDeploy(self.rpc, period=period, sink_address=self.accounts[9])
self.default_supply = 0
self.default_supply_cap = 0
self.start_block = None
@ -97,13 +97,13 @@ class TestDemurrage(EthTesterCase):
self.start_time = None
def deploy(self, interface):
self.address = self.deployer.deploy(self.rpc, self.accounts[0], interface, supply_cap=self.default_supply_cap)
self.start_block = self.deployer.start_block
self.start_time = self.deployer.start_time
self.tax_level = self.deployer.tax_level
self.period_seconds = self.deployer.period_seconds
self.sink_address = self.deployer.sink_address
def publish(self, interface):
self.address = self.publisher.publish(self.rpc, self.accounts[0], interface, supply_cap=self.default_supply_cap)
self.start_block = self.publisher.start_block
self.start_time = self.publisher.start_time
self.tax_level = self.publisher.tax_level
self.period_seconds = self.publisher.period_seconds
self.sink_address = self.publisher.sink_address
logg.debug('contract address {} start block {} start time {}'.format(self.address, self.start_block, self.start_time))
@ -119,6 +119,13 @@ class TestDemurrage(EthTesterCase):
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):
lower_target = target - (target * (tolerance_ppm / 1000000))
self.assertGreaterEqual(v, lower_target)
@ -144,7 +151,7 @@ class TestDemurrageDefault(TestDemurrage):
nonce_oracle = RPCNonceOracle(self.accounts[0], self.rpc)
c = DemurrageToken(self.chain_spec, signer=self.signer, nonce_oracle=nonce_oracle)
self.deploy(c)
self.publish(c)
self.default_supply = 10**12
self.default_supply_cap = self.default_supply

View File

@ -0,0 +1,218 @@
.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

@ -0,0 +1,5 @@
.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

@ -0,0 +1,22 @@
.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

@ -0,0 +1,3 @@
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,5 @@
chainlib-eth~=0.4.11
chainlib~=0.4.8
eth-erc20~=0.5.5
chainlib~=0.4.12
eth-erc20~=0.7.0
funga-eth~=0.6.0
dexif~=0.0.2

View File

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

View File

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

View File

@ -308,6 +308,30 @@ class TestBasic(TestDemurrageDefault):
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):
nonce_oracle = RPCNonceOracle(self.accounts[0], self.rpc)
c = DemurrageToken(self.chain_spec, signer=self.signer, nonce_oracle=nonce_oracle)

314
python/tests/test_burn.py Normal file
View File

@ -0,0 +1,314 @@
# 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

@ -0,0 +1,114 @@
# 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

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

View File

@ -1,17 +1,19 @@
pragma solidity >= 0.8.0;
import "aux/ABDKMath64x64.sol";
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-License-Identifier: AGPL-3.0-or-later
contract DemurrageTokenSingleNocap {
uint256 constant VALUE_LIMIT = 1 << 63;
struct redistributionItem {
uint32 period;
uint72 value;
uint64 demurrage;
}
redistributionItem[] public redistributions; // uint51(unused) | uint64(demurrageModifier) | uint36(participants) | uint72(value) | uint32(period)
redistributionItem[] public redistributions;
// Account balances
mapping (address => uint256) account;
@ -23,7 +25,7 @@ contract DemurrageTokenSingleNocap {
// Cached demurrage timestamp; the timestamp for which demurrageAmount was last calculated
uint256 public demurrageTimestamp;
// Implements EIP172
// Implements EIP173
address public owner;
address newOwner;
@ -37,8 +39,6 @@ contract DemurrageTokenSingleNocap {
// Implements ERC20
uint256 public immutable decimals;
// Implements ERC20
//uint256 public totalSupply;
uint256 supply;
// Last executed period
@ -48,7 +48,7 @@ contract DemurrageTokenSingleNocap {
uint256 public totalSink;
// Value of burnt tokens (burnt tokens do not decay)
uint256 public burned;
uint256 burned;
// 128 bit resolution of the demurrage divisor
// (this constant x 1000000 is contained within 128 bits)
@ -75,7 +75,7 @@ contract DemurrageTokenSingleNocap {
mapping (address => bool) minter;
// Storage for ERC20 approve/transferFrom methods
mapping (address => mapping (address => uint256 ) ) allowance; // holder -> spender -> amount (amount is subject to demurrage)
mapping (address => mapping (address => uint256 ) ) public allowance; // holder -> spender -> amount (amount is subject to demurrage)
// Address to send unallocated redistribution tokens
address public sinkAddress;
@ -93,7 +93,7 @@ contract DemurrageTokenSingleNocap {
// Implements ERC20
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
// New tokens minted
// Implements Minter
event Mint(address indexed _minter, address indexed _beneficiary, uint256 _value);
// New demurrage cache milestone calculated
@ -109,23 +109,30 @@ contract DemurrageTokenSingleNocap {
//event Debug(bytes32 _foo);
event Debug(int128 indexed _foo, uint256 indexed _bar);
// Emitted when tokens are burned
// Implements Burn
event Burn(address indexed _burner, uint256 _value);
// EIP173
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); // EIP173
// Implements Expire
event Expired(uint256 _timestamp);
// Implements Expire
event ExpiryChange(uint256 indexed _oldTimestamp, uint256 _newTimestamp);
event Cap(uint256 indexed _oldCap, uint256 _newCap);
// Implements Sealer
// Implements Seal
uint256 public sealState;
uint8 constant MINTER_STATE = 1;
uint8 constant WRITER_STATE = 1;
uint8 constant SINK_STATE = 2;
uint8 constant EXPIRY_STATE = 4;
uint8 constant CAP_STATE = 8;
// Implements Seal
uint256 constant public maxSealState = 15;
// Implements Seal
event SealStateChange(bool indexed _final, uint256 _sealState);
@ -157,7 +164,6 @@ contract DemurrageTokenSingleNocap {
sinkAddress = _defaultSinkAddress;
}
// Implements Sealer
function seal(uint256 _state) public returns(uint256) {
require(_state < 16, 'ERR_INVALID_STATE');
require(_state & sealState == 0, 'ERR_ALREADY_LOCKED');
@ -166,7 +172,6 @@ contract DemurrageTokenSingleNocap {
return uint256(sealState);
}
// Implements Sealer
function isSealed(uint256 _state) public view returns(bool) {
require(_state < maxSealState);
if (_state == 0) {
@ -175,17 +180,25 @@ contract DemurrageTokenSingleNocap {
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 {
uint256 r;
uint256 oldTimestamp;
require(!isSealed(EXPIRY_STATE));
require(!expired);
require(msg.sender == owner);
r = periodStart + (_expirePeriod * periodDuration);
require(r > expires);
oldTimestamp = expires;
expires = r;
emit ExpiryChange(oldTimestamp, expires);
}
// Change max token supply.
// Can only increase supply cap, not decrease.
function setMaxSupply(uint256 _cap) public {
require(!isSealed(CAP_STATE));
require(msg.sender == owner);
@ -204,6 +217,7 @@ contract DemurrageTokenSingleNocap {
// Expire the contract if expire is set and we have gone over the threshold.
// 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.
// Implements Expire
function applyExpiry() public returns(uint8) {
if (expired) {
return 1;
@ -222,27 +236,33 @@ contract DemurrageTokenSingleNocap {
}
// Given address will be allowed to call the mintTo() function
// Implements Writer
function addWriter(address _minter) public returns (bool) {
require(!isSealed(MINTER_STATE));
require(!isSealed(WRITER_STATE));
require(msg.sender == owner);
minter[_minter] = true;
return true;
}
// Given address will no longer be allowed to call the mintTo() function
// Implements Writer
function deleteWriter(address _minter) public returns (bool) {
require(!isSealed(MINTER_STATE));
require(!isSealed(WRITER_STATE));
require(msg.sender == owner || _minter == msg.sender);
minter[_minter] = false;
return true;
}
// Implements Writer
function isWriter(address _minter) public view returns(bool) {
return minter[_minter] || _minter == owner;
}
/// Implements ERC20
function balanceOf(address _account) public view returns (uint256) {
int128 baseBalance;
int128 currentDemurragedAmount;
uint256 periodCount;
uint8 expiryState;
baseBalance = ABDKMath64x64.fromUInt(baseBalanceOf(_account));
@ -260,7 +280,6 @@ contract DemurrageTokenSingleNocap {
/// Increases base balance for a single account
function increaseBaseBalance(address _account, uint256 _delta) private returns (bool) {
uint256 oldBalance;
uint256 newBalance;
uint256 workAccount;
workAccount = uint256(account[_account]);
@ -277,7 +296,6 @@ contract DemurrageTokenSingleNocap {
/// Decreases base balance for a single account
function decreaseBaseBalance(address _account, uint256 _delta) private returns (bool) {
uint256 oldBalance;
uint256 newBalance;
uint256 workAccount;
workAccount = uint256(account[_account]);
@ -299,12 +317,14 @@ contract DemurrageTokenSingleNocap {
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
// Triggers tax
function mintTo(address _beneficiary, uint256 _amount) external returns (bool) {
// Implements Minter
function mintTo(address _beneficiary, uint256 _amount) public returns (bool) {
uint256 baseAmount;
require(applyExpiry() == 0);
@ -323,6 +343,18 @@ contract DemurrageTokenSingleNocap {
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
function toRedistribution(uint256 _participants, int128 _demurrageModifier, uint256 _value, uint256 _period) public pure returns(redistributionItem memory) {
redistributionItem memory redistribution;
@ -330,6 +362,7 @@ contract DemurrageTokenSingleNocap {
redistribution.period = uint32(_period);
redistribution.value = uint72(_value);
redistribution.demurrage = uint64(uint128(_demurrageModifier) & 0xffffffffffffffff);
_participants;
return redistribution;
}
@ -392,7 +425,7 @@ contract DemurrageTokenSingleNocap {
return lastRedistribution;
}
function getDistribution(uint256 _supply, int128 _demurrageAmount) public view returns (uint256) {
function getDistribution(uint256 _supply, int128 _demurrageAmount) public pure returns (uint256) {
int128 difference;
difference = ABDKMath64x64.mul(ABDKMath64x64.fromUInt(_supply), ABDKMath64x64.sub(ABDKMath64x64.fromUInt(1), _demurrageAmount));
@ -400,7 +433,7 @@ contract DemurrageTokenSingleNocap {
}
function getDistributionFromRedistribution(redistributionItem memory _redistribution) public returns (uint256) {
function getDistributionFromRedistribution(redistributionItem memory _redistribution) public pure returns (uint256) {
uint256 redistributionSupply;
int128 redistributionDemurrage;
@ -510,6 +543,7 @@ contract DemurrageTokenSingleNocap {
return (block.timestamp - _target) / 60;
}
// Equality check for empty redistribution data
function isEmptyRedistribution(redistributionItem memory _redistribution) public pure returns(bool) {
if (_redistribution.period > 0) {
return false;
@ -547,7 +581,8 @@ contract DemurrageTokenSingleNocap {
return ABDKMath64x64.toUInt(r);
}
// Implements ERC20, triggers tax and/or redistribution
// Triggers tax and/or redistribution
// Implements ERC20
function approve(address _spender, uint256 _value) public returns (bool) {
uint256 baseValue;
uint8 ex;
@ -564,7 +599,14 @@ contract DemurrageTokenSingleNocap {
changePeriod();
baseValue = toBaseAmount(_value);
// dex code will attempt uint256max approve, but contract cannot handle that size
// truncate to biggest possible value
if (_value <= VALUE_LIMIT) {
baseValue = toBaseAmount(_value);
} else {
baseValue = VALUE_LIMIT;
}
allowance[msg.sender][_spender] = baseValue;
emit Approval(msg.sender, _spender, _value);
return true;
@ -597,7 +639,8 @@ contract DemurrageTokenSingleNocap {
return true;
}
// Implements ERC20, triggers tax and/or redistribution
// Triggers tax and/or redistribution
// Implements ERC20
function transfer(address _to, uint256 _value) public returns (bool) {
uint256 baseValue;
bool result;
@ -617,7 +660,8 @@ contract DemurrageTokenSingleNocap {
return result;
}
// Implements ERC20, triggers tax and/or redistribution
// Triggers tax and/or redistribution
// Implements ERC20
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
uint256 baseValue;
bool result;
@ -643,8 +687,6 @@ contract DemurrageTokenSingleNocap {
// ERC20 transfer backend for transfer, transferFrom
function transferBase(address _from, address _to, uint256 _value) private returns (bool) {
uint256 period;
decreaseBaseBalance(_from, _value);
increaseBaseBalance(_to, _value);
@ -653,26 +695,22 @@ contract DemurrageTokenSingleNocap {
// Implements EIP173
function transferOwnership(address _newOwner) public returns (bool) {
require(msg.sender == owner);
newOwner = _newOwner;
}
// Implements OwnedAccepter
function acceptOwnership() public returns (bool) {
address oldOwner;
require(msg.sender == newOwner);
oldOwner = owner;
owner = newOwner;
newOwner = address(0);
require(msg.sender == owner);
oldOwner = owner;
owner = _newOwner;
emit OwnershipTransferred(oldOwner, owner);
return true;
}
// Explicitly and irretrievably burn tokens
// Only token minters can burn tokens
function burn(uint256 _value) public {
// Implements Burner
function burn(uint256 _value) public returns(bool) {
require(applyExpiry() == 0);
require(minter[msg.sender]);
require(minter[msg.sender] || msg.sender == owner, 'ERR_ACCESS');
require(_value <= account[msg.sender]);
uint256 _delta = toBaseAmount(_value);
@ -680,6 +718,19 @@ contract DemurrageTokenSingleNocap {
decreaseBaseBalance(msg.sender, _delta);
burned += _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
@ -688,25 +739,45 @@ contract DemurrageTokenSingleNocap {
}
// Return total number of burned tokens
// Implements Burner
function totalBurned() public view returns (uint256) {
return burned;
}
// Return total number of tokens ever minted
// Implements Burner
function totalMinted() public view returns (uint256) {
return supply;
}
// Implements EIP165
function supportsInterface(bytes4 _sum) public pure returns (bool) {
if (_sum == 0xc6bb4b70) { // ERC20
if (_sum == 0xb61bc941) { // ERC20
return true;
}
if (_sum == 0x449a52f8) { // Minter
if (_sum == 0x5878bcf4) { // Minter
return true;
}
if (_sum == 0x01ffc9a7) { // EIP165
if (_sum == 0xbc4babdd) { // Burner
return true;
}
if (_sum == 0x9493f8b2) { // EIP173
if (_sum == 0x0d7491f8) { // Seal
return true;
}
if (_sum == 0x37a47be4) { // OwnedAccepter
if (_sum == 0xabe1f1f5) { // Writer
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 false;

View File

@ -5,6 +5,7 @@ all: single_nocap
single_nocap:
$(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 --metadata --evm-version byzantium | awk 'NR==4' > DemurrageTokenSingleNocap.metadata.json
truncate -s -1 DemurrageTokenSingleNocap.bin
single: single_nocap