demmurage

Get to know Catallax: Selective Citizenship and Citizen Override

This is the fourth part in a five part series of posts that lay out the basics of what we are trying to build with Catallax.  The series will follow the following schedule and I’ll update the list with links as the articles go live:

  1. Demurrage, Catch Up, and Pref Dividends
  2. Passthroughs, Legacy, and Folding the Blockchain
  3. Privacy, Accounts, and Transparency  
  4. Selective Citizenship and Citizen Override (today)
  5. Loans and a new kind of Capitalist

The Catallax system requires some ‘central’ authority to exist to set decay rates and pull the levers of the economy to keep the economic piston pumping.  A huge benefit of cryptocurrencies is the ability to do away with centralization.  In the same way that we took a long / short position on privacy, we will also take a long / short position on centralization.
 
In our opinion, the world is not ready to overthrow the nation state. There may be a day in the distant future where we can reach this kind of reality but we believe that there needs to be a bridge between now and then.  In order to neutralize too much authority, we propose a scenario of Selective Citizenship and the Citizen Override.
 
Selective Citizenship allows for citizen accounts to elect to pay a tax out of their pref flows that go to an institution that they want to be a part of.  These institutions can be State level institutions or something smaller like a local utility district or school system.  We contend that one of the killer apps of ethereum and other cryptocurrencies is taxation.  Once municipalities realize that by issuing their own form of crypto they can make taxation automagical you will begin to see a lot more municipalities issuing crypto.  Catallax seeks to speed this revolution by adding a taxation layer into our system.
 
We are also short authority and believe that citizens should maintain control over the ruling authority.  Therefore we put forward the idea of the citizen override.  The citizen override provides the opportunity for citizens to give an authority the right of easy taxation, but give the citizens an easy way to turn off the faucet and override the ability of the account to operate.
 
An example of how this would work on the largest scale would be the US nationalizing a Catallax currency and enforcing that all citizens elect the USA tax.  This tax mechanism replaces the IRS.  In return citizens now have a method to turn off the faucet by voting.  If Congress reaches a 23% approval rating like they have now, the citizens that pay the tax can turn off the government's access to pay representatives their salaries.
 
In a more realistic scenario, the first Catallax system will start in a state of benevolent dictatorship, evolve an authoritative court system, establish a legislative council that will turn into an elected body and then eventually pass to a form of constitutional organization where citizens have significantly more control over their governments than they currently do.
 
Our civic institutions have taken a serious hit in the last few decades as capitalistic organizations have found profit avenues that have made us less dependent on those civic organizations.  The Selective Citizenship system seeks to restore that civic infrastructure by giving grassroots organizations a dead simple way to generate revenue.  Because the money that is taxed is money that is already flowing away from citizens it is much easier to convince someone to elect the tax. They are going to be losing the money anyway, so why not have it go to a group seeking to improve the local street infrastructure or establish new green spaces?
 
This governance may be one of the last parts of the system to come online, but it is one of the most important pieces and any of our supporters should demand that these items stay central to the conversation of Catallax and its future.

If this is interesting to you and you'd like to see where we are going with Catallax, please pick up my book Immortality (Purchase of a physical or kindle copy helps support this project).

Donations always accepted at:

BTC: 1AAfkhg1NEQwGmwW36dwDZjSAvNLtKECas

ETH and Tokens: 0x148311c647ec8a584d896c04f6492b5d9cb3a9b0

If you would like more code articles like this please consider becoming a patron on patreon.

Testing With Time - Dev Log 7

Weekly Update

  1. I’m a Dad again(for the fourth time).  Weston James was born on Tuesday evening June the 20th.  Mom and baby are healthy.  Big Bro, Big Sis, and Big Sis 2 are super excited, and Dad is really proud.
  2. I guess I’m a professional solidity developer as someone paid me actual money(well ETH) for the contract we are discussing today.  Not a lot, but enough be significant.
  3. Work continues on the whitepaper for the first service offering that Catallax will be trying to launch.  Lawyers, accountants, legalese, etc., etc.

Today we are going to do some testing with time.  The is going to be very important once we start testing our demurrage code.  In our decaying token we used passing block numbers to calculate our decay periods.  In the example today we are going to use the actual time system in Ethereum.  This system isn’t an exact science since we are somewhat dependent on the Miners to give a truthful timestamp on each block.  You would not use this system if you were doing calculations on short time scales because a miner could attempt to cheat your contract.  Our example today uses month long periods so we should be fine using time.
 
The contract we are going to develop is called a DisciplineWallet.  Do you have lambo money from buying into the ethereum crowdsale two years ago?  Afraid you’re going to get spooked and sell?  Use the DisciplineWallet and restrict access to your ETH on a monthly basis.
 
When we first started talking about this contract the client wanted the payout to be consistent in USD.  We went back and forth and finally decided that we needed to do it in ETH because there isn’t really a good USD to ETH Oracle that is reliable over long periods of time.  If you know of one, please let me know and I’ll try to update this contract to do USD instead.
 
Our contract will do the following:

  • Be initialized with a term in months and an amount of ETH to pay out each month
  • Take Deposits in ETH
  • Expose a Withdraw function that can be called once a month to send the specified amount of ETH to the owner of the contract
  • Let us change the owner of the contract
  • Withdraw all the remaining ETH to a specified address once the term has run its course
  • Give us a safety function to move coins out of the contact if we accidentally send ERC20 tokens to the contract
  • Use the fallback function as a deposit function
  • Tell us when the next withdrawal is available

Once we write up our contract we are going to want to test it.  To do this we are going to need a blockchain environment that will let us make time go by quickly. Fortunately, the testrpc that is packaged with the truffle dev environment lets us do this with the following call:

web3.currentProvider.sendAsync({
       jsonrpc: "2.0",
       method: "evm_increaseTime",
       params: [86400 * 34],
       id: new Date().getTime()
     }


In the above example, we are moving the clock forward 34 days(86400 seconds in a day).  Our tests will do withdrawals and then move the clock forward and do withdrawals again.
 
Our contract will need to pass the following tests:
 
    ✓ should Deploy a wallet with owner (91ms)
    ✓ should be off when it starts and has no ether (69ms)
    ✓ should have a function Period that returns the length of a month (102ms)
    ✓ should have a function NextWithdraw that returns the first withdraw time (94ms)
    ✓ should turn on when sent ether (775ms)
    ✓ should fail if constructor sent ether
    ✓ should allow withdraw after 1 month and ether goes to owner (750ms)
    ✓ should fail on instant withdraw (255ms)
    ✓ should not allow more than term number of withdraws (955ms)
    ✓ should not allow withdraw if some time has passed, but not enough (382ms)
    ✓ should allow withdraw all after term is over (3389ms)
    ✓ should fail if withdrawAll is called before term is over (388ms)
    ✓ should reject payment if payout term is expired (2778ms)
    ✓ should deposit using deposit function (245ms)
    ✓ should allow for transfer of owner (1529ms)
    ✓ should reduce payout if payout would drain account before the end of the term (679ms)

The code and truffle set up can be found on GitHub here. 
Here is our contact.

pragma solidity ^0.4.11;

contract DisciplineWallet {

  /**
  * @dev term is the number of months that a wallet will pay out
  */
  uint16 public term;


  /**
  * @dev currentTerm tracks the number of withdraws that have occured
  */
  uint16 public currentTerm;

  /**
  * @dev contractStart stores the timestamp(number of seconds since 1/1/1970) that the contract was created
  */
  uint public contractStart;

  /**
  * @dev payout is the number of wei(smallest unit of ETH) to pay out
  */
  uint public payout;


  /**
  * @dev bActive is tracks if the wallet is open for business or not
  */
  bool public bActive;
  address public owner;

  /**
   * @dev Throws if called by any account other than the owner.
   */
  modifier onlyOwner() {
    if (msg.sender != owner) {
      throw;
    }
    _;
  }

  /**
   * @dev constructor
   * @param termLength number of months that the contract will be active
   * @param weiOutputPerPeriod of wei to pay out
   */
  function DisciplineWallet(uint16 termLength, uint weiOutputPerPeriod) {

    if(termLength < 1) throw; //term cant be 0
    if(weiOutputPerPeriod < 1) throw; //we cant pay out 0

    //the owner will start as the address creating the contract
    owner = msg.sender;

    //set the term
    term = termLength;

    //record the time of the start contract
    contractStart = now;

    //start with the current term as 1
    currentTerm = 1;

    //set the payout per period
    payout = weiOutputPerPeriod;
  }


  /**
   * @dev calculates the length of a month
   */
  function Period() constant returns (uint32 lengthOfMonth){
    //put this in a constant function so that we don't have to use storage
    //execution takes 302 gas which means calculation is more efficent in any contract under 66 months.
    //not sure about deployment costs
    //the period is about 30.66 days so that leap year is taken into account every 4 years.
    return (1 years / 12) + (1 days / 4);
  }

  /**
   * @dev tells us what date we can call the withdraw function
   */
  function NextWithdraw() constant returns(uint secondsAfter1970){
    return contractStart + (Period() * currentTerm);
  }

  /**
   * @dev the fallback function will make a deposit
   */
  function () payable{
    Deposit();
  }

  /**
   * @dev Put ETH into the contract, also called by the fallback function
   */
  function Deposit() payable {
    //don't accept ether if the term is over
    if(currentTerm > term) throw;
    if(bActive == false){
      //first time we get ether, turn on the contract
      bActive = true;
    }
  }

  /**
   * @dev Withdraw will send the payout to the owner if enough time has passed
   */
  function Withdraw() onlyOwner returns(bool ok){
    if(currentTerm <= term && now > NextWithdraw()){

      //payout may not be more than balance / term or the account has been underfunded
      //if it is then use the lower calculatio
      if(payout < (this.balance / (term - currentTerm + 1))){
        owner.transfer(payout);
      }
      else{
        owner.transfer(this.balance / term);
      }

      currentTerm = currentTerm + 1;

      if (currentTerm > term){
        bActive = false;
      }

      return true;
    } else{
      throw;
    }

  }


  /**
   * @dev once all terms have expired you can move any remaining ETH to another account
   * @param targetAddress The address to transfer remaining ETH to.
   */
  function WithdrawAll(address targetAddress) onlyOwner returns(bool ok){
    if (targetAddress == 0x0) throw; //dont accidentally burn ether
    if(currentTerm > term && this.balance > 0){
      targetAddress.transfer(this.balance);
      bActive = false;
      return true;
    } else {
      throw;
    }

  }

  /**
   * @dev Allows the current owner to transfer control of the contract to a newOwner.
   * @param newOwner The address to transfer ownership to.
   */
  function transferOwnership(address newOwner) onlyOwner {
    if (newOwner != address(0)) {
      owner = newOwner;
    }
  }

  /**
   * @dev Allows the owner to send tokens elsewhere that were accidentally sent to this account
   * @param Token The address of the ERC20 token
   * @param _to The address the tokens should end up at
   * @param _value The amount of tokens
   */
  function safetyTransferToken(address Token, address _to, uint _value) onlyOwner returns (bool ok){
    bytes4 sig = bytes4(sha3("transfer(address,uint256)"));
    return Token.call(sig, _to, _value);
  }

}


The tests are in CoffeeScript and can easily be compiled to js. The core test concept here is the passage of time.
 
In the "it should allow withdraw after 1 month and ether goes to owner" test we simulate the passing of 34 days via our testrpc evm_increaseTime function mentioned earlier.

Our test code needs to do this multiple time over a set amount of time.  I use a variant of the following function:

withdrawFunction = ()->
  return q.Promise (resolve, reject)->
    web3.currentProvider.sendAsync
      jsonrpc: "2.0",
      method: "evm_increaseTime",
      params: [86400 * 34],  # 86400 seconds in a day
      id: new Date().getTime()
    , (err)->
      i.Withdraw(from: accounts[0])
      .then (result)->
        resolve result
      .catch (err)->
        reject err

We can call it in a loop like this:

async.eachSeries [1..13], (item, done)->
        #console.log item
        withdrawFunction()
        .then (result)->
          i.currentTerm.call(from: accounts[0])
        .then (result)->
          #console.log result
          done()
        .catch (err)->
          #console.log err
          done(err)
    .then (result)->
      assert(false, "shouldnt be here")
    .catch (error)->
      if error.toString().indexOf("invalid op") > -1
        #console.log("We were expecting a Solidity throw (aka an invalid op), we got one. Test succeeded.")
        assert.equal error.toString().indexOf("invalid op") > -1, true, 'didnt find invalid op throw'
      else
        assert(false, error.toString())
  done()

In the above case we call withdraw 13 times and expect it to fail on the 13th try.
 
We now have a great way to test the passage of time when testing our solidity contracts.  Since Catallax will likely do monthly this avenue of calculation may work.  We could manipulate our Decay Token to use timestamps instead of block numbers.  On the other hand, using block numbers allows us more control if we need to do some emergency decay as a monetary lever.

If this is interesting to you and you'd like to see where we are going with Catallax, please pick up my book Immortality(Purchasing a hard or kindle copy helps support this project.

Donations always accepted at:

BTC: 1AAfkhg1NEQwGmwW36dwDZjSAvNLtKECas

ETH and Tokens: 0x148311c647ec8a584d896c04f6492b5d9cb3a9b0

Get to know Catallax: Demurrage, Catch Up, and Pref Dividends

This is the first part in a five-part series of posts that lay out the basics of what we are trying to build with Catallax.  The series will follow the following schedule and I’ll update the list with links as the articles go live: 

  1. Demurrage, Catch Up, and Pref Dividends (today)

  2. Passthroughs, Legacy, and Folding the Blockchain

  3. Privacy, Accounts, and Transparency

  4. Selective Citizenship and Citizen Override

  5. Loans and a new kind of Capitalist

Demurrage, Catch Up, and Pref Dividends

The hook of this system is built on Silvio Gesell’s concept of Natural Money as described in his book ‘The natural economic Order.'

Natural money is ‘natural’ because it decays like all kinds of real capital. Historically, this kind of money was implemented using stamped money.  With stamped money you would have to buy a stamp(say for 1 cents) and affix it to your physical $1 bill once a month(thus having a 12% decay rate).  At the end of each year, all bills would be turned in for new bills. Stamps are a bit impractical in the real world and we are able to do away with them because of the blockchain.  Instead of charging for a stamp, we just track the decay rate and make sure that each account that uses the system pays the correct fee before they are able to transfer money.  We call this the Catch-Up.  I’ve laid out a simple way to do this in solidity in a dev log post.

This is a decent system for accelerating the flow of cash through an economy.  If you cash is going to decay you want to quickly find a place to spend/invest it so that someone else takes on the burden of paying the decay fee.  You will typically find people willing to pay the fee in exchange for reducing risk elsewhere.  As a result, your cash ends up being more efficient as a liquidity tool. 

Implementing a decaying currency is all well and good, but what to do with the decay?  Other blockchains have tried allocating this a miner reward friecoin.  In other stamped money systems the decay fee was used to provide government services and treated like a tax.  We are going to do something different with our decay fees.  We are going to treat the blockchain as a time machine and pass the decay backward through the blockchain to the people that paid into an account.  We call these Pref Dividends.  By doing this we not only incentivise the application of cash so one does not have to pay the decay fee, but we incentivise the application of cash to destinations that the cash holder anticipates will be good at attracting more cash in the future.

Let's take a look at a couple of examples of how this system would work.

Scenario 1 - The Wine Heiress:

A wine merchant produces a bottle of stunning wine.  I think this bottle of wine is worth $20 and the merchant agrees.  This is her first catallaxian transaction so when I give her $20 for the wine, I get 20 pref shares in her account.  I own 100% of the pref shares at this point.  The next day she finds out that a Catallaxian great uncle has passed away and she has inherited a cool $1 million.  She idles the day away dreaming of what she is going to spend this money on.  When she goes to start spending it the next day she has to ‘Catch Up’.  She held $1,000,020 for 1 day at a 12% per year decay rate.  Her first transaction will have a $328 decay fee tacked onto it.  That $328 will go straight into my account because I’m the only one who has ever put cash into her account. Not a bad return on spending $20...and I get to keep the wine.

This is a far-fetched scenario, but it shows the power of betting right.

Scenario 2:  The Established Merchant.

Like the last scenario, I’m going to buy a bottle of wine for $20. But this time I’m buying it from a wine merchant who has been growing their operation for a while and is established in the business.  I get the same 20 pref points in the account, but in this scenario, the merchant has already had revenues of $3,000,000 over the course of her operation.  As a result, my $20 only makes up 0.00000666666 of the total 3,000,020 prefs.  If this merchant likes to keep $100,000 in their account to mitigate risk, my one day's worth of pref payments(at a 12% decay rate) would only be $0.0002.  What a tiny sum!  Over a year that is only $.073 cents.

From this scenario, we learn that one shouldn’t expect grand riches from this setup, but if one were to buy a bottle of wine a week for 20 years you’d end up with a stipend of $75 / year for your participation in the Wine Economy. (This is a rough calculation and doesn’t take into account reduction in percentage of the wine merchant's account).  This is not a great ROI, but don’t forget, you still have all that wine.

The moral of these two stories is that over a lifetime of spending money with accounts that range in return between these two scenarios one can build up a nice recurring pref payment that can act as a form of earned basic income.

In addition, we have some new levers on the economy that we can pull to try to accelerate the velocity of money, combat inflation, and increase redistribution of wealth while maintaining the market incentives of capitalism.

Statutory Theft

One principle must be put in place for this all to work properly and that is the principle of the inalienable right to pref ownership.  This means that you cannot sell your prefs anymore than you can sell yourself into slavery.  I propose the concept of statutory theft as a legal guiding principle of how handle scams and inappropriate attempts to confiscate the value of future pref payments.  This is a difficult thing to implement in code and will be an important reason that we will need to look at rule of law in relation to deploying the Catallax system.

You can read more and explore the economic model I’ve built showing how this system can lead to increases in GDP and reduction in poverty in one of my other articles:  http://catallax.info/news/2015/4/19/a-published-model-of-hypercapitalism

If this is interesting to you and you'd like to see where we are going with Catallax, please pick up my book Immortality.

Donations always accepted at:

BTC: 1AAfkhg1NEQwGmwW36dwDZjSAvNLtKECas

ETH and Tokens: 0x148311c647ec8a584d896c04f6492b5d9cb3a9b0

To Part 2:  Pass Through, Legacy, and Folding the Blockchain

A Decaying Token - Building Catallax on Ethereum - Week 3

The last couple of weeks of chasing rabbit trails to try to figure out how to deliver pref payments out to accounts once a Catallax account has caught up has settled down this week due to making the following assumption:

An outside authority is going to have to keep track of and distribute pref payments.

I’ll get back to this in future development.  I may even find an on-chain solution, but until then I’m going to just table it and build out some of the other features.

Today I’m publishing some actual working solidity code that runs a decaying token.

You can see the contract at the bottom of this article or here:

https://gist.github.com/anonymous/7fc3f3a48ad3e8b26aa1a7c55030c64f

You can load it up in browser solidity here:

https://ethereum.github.io/browser-solidity/#gist=7fc3f3a48ad3e8b26aa1a7c55030c64f

I’ve stripped out the extraneous erc20 stuff and just focused on balances at the moment.  We are doing something pretty basic here.  We have a structure called a rateMap (mapping(uint -> Rate)) that is going to keep track of ranges of blocks and an associated decay rate.  If your account isn’t caught up to the latest maxCatchUpBlock, you can’t spend your tokens and must first ‘catch up’ before you can spend again.

In this example, we are trusting and outside authority to publish reliable rates and currently, the decayed tokens just collect in an internal variable in the contract(demurrageHold).

The Rate Struct looks like this:

struct Rate {
  uint256 nextblock;
  uint256 rate;
  bool initilized;
}

The nextblock variable points to the place in the rateMap mapping where you can find the next rate.  The initialized bool is used to validate that a rate that you have found in your rateMap is a valid rate.  Empty mappings will return an uninitialized struct so this lets us look up a rate and know that it is invalid.

When we start our contract we seed the rateMap like this:

//record the startblock that the currency came online -- used for cycling through rates
  startBlock = block.number;

  //create the first rate that goes from block 0 to the start block
  rateMap[0].initialized = true;
  rateMap[0].rate = 0;
  rateMap[0].nextblock = startBlock;

  //init the next rate
  rateMap[startBlock].initialized = true;

  //set the max catchup to the current block
  maxCatchUpBlock = block.number;

  rateBase = 10000000; //base used for rates.

So starting off we will have a rate from 0 to our startBlock of 0 and we will be waiting for the rate to be added with an initialized rate at the startBlock. 

You can observe the decaying currency by executing the following in browser solidity:

  1. Publish the contract with a call of 1000000000,””,2,””  - this creates a billion tokens and puts them in originator’s account.  Let’s assume this is 0xca35b7d915458ef540ade6068dfe2f44e8fa733c

  2. Note the startBlock variable and capture that.  We’re going to add our first decay rate by calling addRate with StartBlock, StartBlock + 100, 700000. Ie:  1150000,1150100, 700000 -Note that the rate we are putting in (700000) will be made a percentage by dividing by the baseRate Variable in our contract.  So in this instance we are decaying 7% over a 100 block period.  Pretty steep, but good for our example.

  3. Try transferring some tokens to another address by calling transfer(Ie:  "0x14723a09acff6d2a60dcdf7aa4aff308fddc160c", 100).  The function should throw since the maxCatchUpBlock has increased from our current maxCatcUpBlock for our original address of 0.

  4. In increase our catchUpBlock for our account we need to catch it up.  Call CatchUp with your account number.  Ie 0xca35b7d915458ef540ade6068dfe2f44e8fa733c

  5. Check your balanceOf your account and you should see that it is 70,000,000 tokens lighter.  These tokens are in the demurrageHold variable.

  6. Try your transfer from #3 above.  It should go through this time.

  7.  Notice that in the transfer we have to initialize the new account that is created with a catchUpBlock equal to the maxCatchUpBlock(1150100).  If we didn’t do this then the first time this account caught up it would start at block 0 even though it didn’t have any tokens from 1150000 to 1150100.

This token doesn’t do much except decay at a rate specified by the publisher.  There is a lot of work left to do, but it is nice to have some actual code that does something interesting.

Next week I’ll get back to putting some of the infrastructure necessary to issue out pref payments and maybe start looking at how to determine what those payments are processing the blockchain.

If you have any comments or questions, please leave them below. If you’d like to see more of this kind of stuff and help us build this new economy please consider supporting the "Catallax Code " patreon.

If this is interesting to you and you'd like to see where we are going with Catallax, please pick up my book Immortality.

Donations always accepted at:

BTC: 1AAfkhg1NEQwGmwW36dwDZjSAvNLtKECas

ETH and Tokens: 0x148311c647ec8a584d896c04f6492b5d9cb3a9b0

//© copyright 2017 - Catallax Bank and Rivvir Consulting
// Developed by Austin Fatheree
// http://catallax.info  @hypercatallax
// All rights reserved. 
pragma solidity ^0.4.8;

contract DecayToken {

struct Rate {
  uint256 nextblock;
  uint256 rate;
  bool initialized;
}

uint256 public totalSupply;
uint256 public startBlock; //holds the generation block for the contract so that we know where to start our linked list for decay rates
uint256 public demurrageHold;
uint256 public rateBase;
uint256 maxCatchUpBlock;

mapping(address => uint256) balance;
mapping(address => uint256) catchUpBlock;

mapping(uint256 => Rate) rateMap;

string public name;                   //fancy name: eg Simon Bucks
uint8 public decimals;                //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether.
string public symbol;                 //An identifier: eg SBX
string public version = 'H0.1';       //human 0.1 standard. Just an arbitrary versioning scheme.



function () {
    //if ether is sent to this address, send it back.
    throw;
}

function DecayToken(
    uint256 _initialAmount,
    string _tokenName,
    uint8 _decimalUnits,
    string _tokenSymbol
){

  balance[msg.sender] = _initialAmount;               // Give the creator all initial tokens

  totalSupply = _initialAmount;                        // Update total supply
  name = _tokenName;                                   // Set the name for display purposes
  decimals = _decimalUnits;                            // Amount of decimals for display purposes
  symbol = _tokenSymbol;                               // Set the symbol for display purposes

  //record the startblock that the currency came online -- used for cycling through rates
  startBlock = block.number;

  //create the first rate that goes from block 0 to the start block
  rateMap[0].initialized = true;
  rateMap[0].rate = 0;
  rateMap[0].nextblock = startBlock;

  //init the next rate
  rateMap[startBlock].initialized = true;

  //set the max catchup to the current block
  maxCatchUpBlock = block.number;

  rateBase = 10000000; //base used for rates.
}

//erc20 interface
function balanceOf( address who ) constant returns (uint value){
  //todo: check validity
  return balance[who];
}

function transfer( address to, uint value) returns (bool ok){

  if(value == 0) throw;

  //test catch up
  if(catchUpBlock[msg.sender] < maxCatchUpBlock) throw;

  //make sure balance is positive
  if(balance[msg.sender] < value) throw;

  //update balances
  balance[msg.sender] = balance[msg.sender] - value;

  //if this is a new account or the previous balance was 0, catch it up by default
  if(balance[to] == 0){
    catchUpBlock[to] = maxCatchUpBlock;
  }
  balance[to] = balance[to] + value;


  Transfer(msg.sender, to, value);
  return true;
}

function addRate(uint _startBlock, uint _endBlock, uint amount) returns (bool ok){

  if(rateMap[_startBlock].initialized == false) throw; //a rate doesnt exist for this startblock

  if(rateMap[_endBlock].initialized != false) throw; //we cant correct rates here only append
  //set the new rate
  rateMap[_startBlock].nextblock = _endBlock;
  rateMap[_startBlock].rate = amount;
  rateMap[_endBlock].initialized = true;

  //update the maxCatchUpBlock for everyoune
  maxCatchUpBlock = _endBlock;
  return true;
}

function getRate(uint _startBlock) constant returns(uint _TheRate, uint _EndBlock){
  _TheRate = rateMap[_startBlock].rate;
  _EndBlock = rateMap[_startBlock].nextblock;
}

function catchup(address account) returns (bool ok){

  //todo: issuer can force catchup
  if(msg.sender != account) throw;


  uint transferAmount = 0; //the amount that will decay
  uint nextblock = catchUpBlock[account]; //lookup the current catchup block for this account
  uint startBalance = balance[account]; //lookup the current balance of an account

  //loop through each rate from the last catch up to maxCatchUpBlock and decay the cash
  while(nextblock < maxCatchUpBlock){
    Rate thisrate = rateMap[nextblock]; //what was the rate during this period?
    uint removeAmount = (startBalance * thisrate.rate)/rateBase; //calculate the amount
    transferAmount = transferAmount + removeAmount;  //store the amount
    startBalance = startBalance - removeAmount; //adjust balance used in calc so we don't go below 0
    nextblock = thisrate.nextblock; // update nextblock to advance loop
    //todo:  scheme to check remaining gas and bail if gas gets too low
  }

  balance[account] = balance[account] - transferAmount;  //update the balance
  demurrageHold = demurrageHold + transferAmount; //put the decayed amount into a place for everyone to see

  catchUpBlock[account] = maxCatchUpBlock; //update the catchup block allowing the account to spend

  CatchUp(account, maxCatchUpBlock, transferAmount);  //broadcast catchup so issuer can act
  return true;

}

event CatchUp(address indexed from, uint newMaxBlock, uint value);
event Transfer( address indexed from, address indexed to, uint value);

}