Advertisement
Guest User

Untitled

a guest
Oct 18th, 2019
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 25.40 KB | None | 0 0
  1. pragma solidity ^ 0.5.11;
  2. contract Pyramid{
  3. // scaleFactor is used to convert Ether into bonds and vice-versa: they're of different
  4. // orders of magnitude, hence the need to bridge between the two.
  5. uint256 constant scaleFactor = 0x10000000000000000;
  6.  
  7. int constant crr_n = 1;
  8. int constant crr_d = 2;
  9.  
  10. int constant public price_coeff = -0x1337FA66607BADA55;
  11.  
  12. // Typical values that we have to declare.
  13. string constant public name = "Bond";
  14. string constant public symbol = "BOND";
  15. uint8 constant public decimals = 12;
  16.  
  17. // Array between each address and their number of bonds.
  18. mapping(address => uint256) public hodlBonds;
  19. // For calculating resolves minted
  20. mapping(address => uint256) public avgFactor_ethSpent;
  21. // For calculating hodl multiplier that factors into resolves minted
  22. mapping(address => uint256) public avgFactor_buyInTimeSum;
  23. // Array between each address and their number of resolves being staked.
  24. mapping(address => uint256) public resolveWeight;
  25.  
  26. // Array between each address and how much Ether has been paid out to it.
  27. // Note that this is scaled by the scaleFactor variable.
  28. mapping(address => int256) public payouts;
  29.  
  30. // Variable tracking how many bonds are in existence overall.
  31. uint256 public _totalSupply;
  32.  
  33. // The total number of resolves being staked in this contract
  34. uint256 public dissolvingResolves;
  35. // The total number of resolves burned for a return of ETH(withdraw) or Bonds(reinvest)
  36. uint256 public dissolved;
  37.  
  38. // The ethereum locked up into bonds
  39. uint public contractBalance;
  40.  
  41. // Easing in the fee. Make the fee reasonable as the contract is scaling to the size of the ecosystem
  42. uint256 public buySum;
  43. uint256 public sellSum;
  44.  
  45. // For calculating the hodl multiplier. Weighted average release time
  46. uint public avgFactor_releaseWeight;
  47. uint public avgFactor_releaseTimeSum;
  48. // base time on when the contract was created
  49. uint public genesis;
  50.  
  51. // Aggregate sum of all payouts.
  52. // Note that this is scaled by the scaleFactor variable.
  53. int256 totalPayouts;
  54.  
  55. // Variable tracking how much Ether each token is currently worth.
  56. // Note that this is scaled by the scaleFactor variable.
  57. uint256 earningsPerResolve;
  58. uint remainderForDividends;
  59.  
  60. //The resolve token contract
  61. ResolveToken public resolveToken;
  62.  
  63. constructor() public{
  64. genesis = now;
  65. resolveToken = new ResolveToken( address(this) );
  66. }
  67.  
  68. function totalSupply() public view returns (uint256) {
  69. return _totalSupply;
  70. }
  71. function getResolveContract() public view returns(address){ return address(resolveToken); }
  72. // Returns the number of bonds currently held by _owner.
  73. function balanceOf(address _owner) public view returns (uint256 balance) {
  74. return hodlBonds[_owner];
  75. }
  76.  
  77. function fluxFee(uint paidAmount) public view returns (uint fee) {
  78. if (dissolvingResolves == 0)
  79. return 0;
  80.  
  81. uint totalResolveSupply = resolveToken.totalSupply() - dissolved;
  82. return paidAmount * dissolvingResolves / totalResolveSupply * sellSum / buySum;
  83. }
  84.  
  85. // Converts the Ether accrued as resolveEarnings back into bonds without having to
  86. // withdraw it first. Saves on gas and potential price spike loss.
  87. event Reinvest( address indexed addr, uint256 reinvested, uint256 dissolved, uint256 bonds, uint256 resolveTax);
  88. function reinvestEarnings(uint amountFromEarnings) public returns(uint,uint){
  89. // Retrieve the resolveEarnings associated with the address the request came from.
  90. uint totalEarnings = resolveEarnings(msg.sender);
  91. require(amountFromEarnings <= totalEarnings, "the amount exceeds total earnings");
  92. uint oldWeight = resolveWeight[msg.sender];
  93. resolveWeight[msg.sender] = oldWeight * (totalEarnings - amountFromEarnings) / totalEarnings;
  94. uint weightDiff = oldWeight - resolveWeight[msg.sender];
  95. dissolved += weightDiff;
  96. dissolvingResolves -= weightDiff;
  97.  
  98. // For maintaing payout invariance
  99. int resolvePayoutDiff = (int256) (earningsPerResolve * weightDiff);
  100.  
  101. payouts[msg.sender] += resolvePayoutDiff;
  102.  
  103. totalPayouts += resolvePayoutDiff;
  104.  
  105. // Assign balance to a new variable.
  106. uint value_ = (uint) (amountFromEarnings);
  107.  
  108. // If your resolveEarnings are worth less than 1 szabo, abort.
  109. if (value_ < 0.000001 ether)
  110. revert();
  111.  
  112. // msg.sender is the address of the caller.
  113. address sender = msg.sender;
  114.  
  115. // Calculate the fee
  116. uint fee = fluxFee(value_);
  117.  
  118. // The amount of Ether used to purchase new bonds for the caller
  119. uint numEther = value_ - fee;
  120. buySum += numEther;
  121.  
  122. //resolve reward tracking stuff
  123. uint currentTime = NOW();
  124. avgFactor_ethSpent[msg.sender] += numEther;
  125. avgFactor_buyInTimeSum[msg.sender] += currentTime * scaleFactor * numEther;
  126.  
  127. // The number of bonds which can be purchased for numEther.
  128. uint createdBonds = calculateBondsFromReinvest(numEther, amountFromEarnings);
  129.  
  130. // the variable storing the amount to be paid to stakers
  131. uint resolveFee;
  132.  
  133. // Check if we have bonds in existence
  134. if (_totalSupply > 0 && fee > 0) {
  135. resolveFee = fee * scaleFactor;
  136.  
  137. // Fee is distributed to all existing resolve stakers before the new bonds are purchased.
  138. // rewardPerResolve is the amount(ETH) gained per resolve token from this purchase.
  139. uint rewardPerResolve = resolveFee/dissolvingResolves;
  140.  
  141. // The Ether value per token is increased proportionally.
  142. earningsPerResolve += rewardPerResolve;
  143. }
  144.  
  145. // Add the createdBonds to the total supply.
  146. _totalSupply += createdBonds;
  147.  
  148. // Assign the bonds to the balance of the buyer.
  149. hodlBonds[sender] += createdBonds;
  150.  
  151. emit Reinvest(msg.sender, value_, weightDiff, createdBonds, resolveFee);
  152. return (createdBonds, weightDiff);
  153. }
  154.  
  155. // Sells your bonds for Ether
  156. function sellAllBonds() public {
  157. sell( balanceOf(msg.sender) );
  158. }
  159. function sellBonds(uint amount) public returns(uint,uint){
  160. uint balance = balanceOf(msg.sender);
  161. require(balance >= amount, "Amount is more than balance");
  162. uint returned_eth;
  163. uint returned_resolves;
  164. (returned_eth, returned_resolves) = sell(amount);
  165. return (returned_eth, returned_resolves);
  166. }
  167.  
  168. // Big red exit button to pull all of a holder's Ethereum value from the contract
  169. function getMeOutOfHere() public {
  170. sellAllBonds();
  171. withdraw( resolveEarnings(msg.sender) );
  172. }
  173.  
  174. // Gatekeeper function to check if the amount of Ether being sent isn't too small
  175. function fund() payable public returns(uint){
  176. uint bought;
  177. if (msg.value > 0.000001 ether) {
  178. contractBalance += msg.value;
  179. bought = buy();
  180. } else {
  181. revert();
  182. }
  183. return bought;
  184. }
  185.  
  186. // Function that returns the (dynamic) pricing for buys, sells and fee
  187. function pricing(uint scale) public view returns (uint buyPrice, uint sellPrice, uint fee) {
  188. uint buy_eth = scaleFactor * getPriceForBonds( scale, true) / ( scaleFactor - fluxFee(scaleFactor) ) ;
  189. uint sell_eth = getPriceForBonds(scale, false);
  190. sell_eth -= fluxFee(sell_eth);
  191. return ( buy_eth, sell_eth, fluxFee(scale) );
  192. }
  193.  
  194. // For calculating the price
  195. function getPriceForBonds(uint256 bonds, bool upDown) public view returns (uint256 price) {
  196. uint reserveAmount = reserve();
  197.  
  198. if(upDown){
  199. uint x = fixedExp((fixedLog(_totalSupply + bonds) - price_coeff) * crr_d/crr_n);
  200. return x - reserveAmount;
  201. }else{
  202. uint x = fixedExp((fixedLog(_totalSupply - bonds) - price_coeff) * crr_d/crr_n);
  203. return reserveAmount - x;
  204. }
  205. }
  206.  
  207. // Calculate the current resolveEarnings associated with the caller address. This is the net result
  208. // of multiplying the number of resolves held by their current value in Ether and subtracting the
  209. // Ether that has already been paid out.
  210. function resolveEarnings(address _owner) public view returns (uint256 amount) {
  211. return (uint256) ((int256)(earningsPerResolve * resolveWeight[_owner]) - payouts[_owner]) / scaleFactor;
  212. }
  213.  
  214. event Buy( address indexed addr, uint256 spent, uint256 bonds, uint256 resolveTax);
  215. function buy() internal returns(uint){
  216. // Any transaction of less than 1 szabo is likely to be worth less than the gas used to send it.
  217. if ( msg.value < 0.000001 ether )
  218. revert();
  219.  
  220. // Calculate the fee
  221. uint fee = fluxFee(msg.value);
  222.  
  223. // The amount of Ether used to purchase new bonds for the caller.
  224. uint numEther = msg.value - fee;
  225. buySum += numEther;
  226.  
  227. //resolve reward tracking stuff
  228. uint currentTime = NOW();
  229. avgFactor_ethSpent[msg.sender] += numEther;
  230. avgFactor_buyInTimeSum[msg.sender] += currentTime * scaleFactor * numEther;
  231.  
  232. // The number of bonds which can be purchased for numEther.
  233. uint createdBonds = getBondsForEther(numEther);
  234.  
  235. // Add the createdBonds to the total supply.
  236. _totalSupply += createdBonds;
  237.  
  238. // Assign the bonds to the balance of the buyer.
  239. hodlBonds[msg.sender] += createdBonds;
  240.  
  241. // Check if we have bonds in existence
  242. uint resolveFee;
  243. if (_totalSupply > 0 && fee > 0) {
  244. resolveFee = fee * scaleFactor;
  245.  
  246. // Fee is distributed to all existing resolve holders before the new bonds are purchased.
  247. // rewardPerResolve is the amount gained per resolve token from this purchase.
  248. uint rewardPerResolve = resolveFee/dissolvingResolves;
  249.  
  250. // The Ether value per resolve is increased proportionally.
  251. earningsPerResolve += rewardPerResolve;
  252. }
  253. emit Buy( msg.sender, msg.value, createdBonds, resolveFee);
  254. return createdBonds;
  255. }
  256. function NOW() public view returns(uint time){
  257. return now - genesis;
  258. }
  259. function avgHodl() public view returns(uint hodlTime){
  260. return avgFactor_releaseTimeSum / avgFactor_releaseWeight / scaleFactor;
  261. }
  262. function getReturnsForBonds(address addr, uint bondsReleased) public view returns(uint etherValue, uint mintedResolves, uint new_releaseTimeSum, uint new_releaseWeight, uint initialInput_ETH){
  263. uint output_ETH = getEtherForBonds(bondsReleased);
  264. uint input_ETH = avgFactor_ethSpent[addr] * bondsReleased / hodlBonds[addr];
  265. // hodl multiplier. because if you don't hodl at all, you shouldn't be rewarded resolves.
  266. // and the multiplier you get for hodling needs to be relative to the average hodl
  267. uint buyInTime = avgFactor_buyInTimeSum[addr] / avgFactor_ethSpent[addr];
  268. uint cashoutTime = NOW()*scaleFactor - buyInTime;
  269. uint releaseTimeSum = avgFactor_releaseTimeSum + cashoutTime*input_ETH/scaleFactor/*to give new life more weight--->*/*buyInTime;
  270. uint releaseWeight = avgFactor_releaseWeight + input_ETH/*to give new life more weight--->*/*buyInTime/scaleFactor;
  271. uint avgCashoutTime = releaseTimeSum/releaseWeight;
  272. return (output_ETH, input_ETH * cashoutTime / avgCashoutTime * input_ETH / output_ETH, releaseTimeSum, releaseWeight, input_ETH);
  273. }
  274. event Sell( address indexed addr, uint256 bondsSold, uint256 cashout, uint256 resolves, uint256 resolveTax, uint256 initialCash);
  275. function sell(uint256 amount) internal returns(uint eth, uint resolves){
  276. // Calculate the amount of Ether & Resolves that the holder's bonds sell for at the current sell price.
  277. uint numEthersBeforeFee;
  278. uint mintedResolves;
  279. uint releaseTimeSum;
  280. uint releaseWeight;
  281. uint initialInput_ETH;
  282. (numEthersBeforeFee,mintedResolves,releaseTimeSum,releaseWeight,initialInput_ETH) = getReturnsForBonds(msg.sender, amount);
  283.  
  284. // magic distribution
  285. resolveToken.mint(msg.sender, mintedResolves);
  286.  
  287. // update weighted average cashout time
  288. avgFactor_releaseTimeSum = releaseTimeSum;
  289. avgFactor_releaseWeight = releaseWeight;
  290.  
  291. // reduce the amount of "eth spent" based on the percentage of bonds being sold back into the contract
  292. avgFactor_ethSpent[msg.sender] -= initialInput_ETH;
  293. // reduce the "buyInTime" sum that's used for average buy in time
  294. avgFactor_buyInTimeSum[msg.sender] = avgFactor_buyInTimeSum[msg.sender] * (hodlBonds[msg.sender] - amount) / hodlBonds[msg.sender];
  295.  
  296. // calculate the fee
  297. uint fee = fluxFee(numEthersBeforeFee);
  298.  
  299. // Net Ether for the seller after the fee has been subtracted.
  300. uint numEthers = numEthersBeforeFee - fee;
  301.  
  302. //updating the numerator of the fee-easing factor
  303. sellSum += initialInput_ETH;
  304.  
  305. // Burn the bonds which were just sold from the total supply.
  306. _totalSupply -= amount;
  307.  
  308. // Remove the bonds from the balance of the buyer.
  309. hodlBonds[msg.sender] -= amount;
  310.  
  311.  
  312. // Check if we have bonds in existence
  313. uint resolveFee;
  314. if (_totalSupply > 0 && dissolvingResolves > 0){
  315. // Scale the Ether taken as the selling fee by the scaleFactor variable.
  316. resolveFee = fee * scaleFactor;
  317.  
  318. // Fee is distributed to all remaining resolve holders.
  319. // rewardPerResolve is the amount gained per resolve thanks to this sell.
  320. uint rewardPerResolve = resolveFee/dissolvingResolves;
  321.  
  322. // The Ether value per resolve is increased proportionally.
  323. earningsPerResolve += rewardPerResolve;
  324. }
  325.  
  326. // Send the ethereum to the address that requested the sell.
  327. contractBalance -= numEthers;
  328. msg.sender.transfer(numEthers);
  329. emit Sell( msg.sender, amount, numEthers, mintedResolves, resolveFee, initialInput_ETH);
  330. return (numEthers, mintedResolves);
  331. }
  332.  
  333. // Dynamic value of Ether in reserve, according to the CRR requirement.
  334. function reserve() public view returns (uint256 amount) {
  335. return SafeMath.sub( balance(), (uint256) ((int256) (earningsPerResolve * dissolvingResolves) - totalPayouts) / scaleFactor );
  336. }
  337. function balance() internal view returns (uint256 amount) {
  338. // msg.value is the amount of Ether sent by the transaction.
  339. return contractBalance - msg.value;
  340. }
  341.  
  342. // Calculates the number of bonds that can be bought for a given amount of Ether, according to the
  343. // dynamic reserve and _totalSupply values (derived from the buy and sell prices).
  344. function getBondsForEther(uint256 ethervalue) public view returns (uint256 bonds) {
  345. return SafeMath.sub(fixedExp( fixedLog( reserve() + ethervalue ) * crr_n/crr_d + price_coeff ) , _totalSupply);
  346. }
  347.  
  348. // Semantically similar to getBondsForEther, but subtracts the callers balance from the amount of Ether returned for conversion.
  349. function calculateBondsFromReinvest(uint256 ethervalue, uint256 subvalue) public view returns (uint256 bondTokens) {
  350. return SafeMath.sub(fixedExp(fixedLog(SafeMath.sub(reserve() , subvalue) + ethervalue)*crr_n/crr_d + price_coeff) , _totalSupply);
  351. }
  352.  
  353. // Converts a number bonds into an Ether value.
  354. function getEtherForBonds(uint256 bondTokens) public view returns (uint256 ethervalue) {
  355. // How much reserve Ether do we have left in the contract?
  356. uint reserveAmount = reserve();
  357.  
  358. // If you're the Highlander (or bagholder), you get The Prize. Everything left in the vault.
  359. if (bondTokens == _totalSupply)
  360. return reserveAmount;
  361.  
  362. // If there would be excess Ether left after the transaction this is called within, return the Ether
  363. // corresponding to the equation in Dr Jochen Hoenicke's original Ponzi paper, which can be found
  364. // at https://test.jochen-hoenicke.de/eth/ponzitoken/ in the third equation, with the CRR numerator
  365. // and denominator altered to 1 and 2 respectively.
  366. return SafeMath.sub(reserveAmount, fixedExp( ( fixedLog(_totalSupply-bondTokens)-price_coeff ) * crr_d/crr_n) );
  367. }
  368.  
  369. // You don't care about these, but if you really do they're hex values for
  370. // co-efficients used to simulate approximations of the log and exp functions.
  371. int256 constant one = 0x10000000000000000;
  372. uint256 constant sqrt2 = 0x16a09e667f3bcc908;
  373. uint256 constant sqrtdot5 = 0x0b504f333f9de6484;
  374. int256 constant ln2 = 0x0b17217f7d1cf79ac;
  375. int256 constant ln2_64dot5 = 0x2cb53f09f05cc627c8;
  376. int256 constant c1 = 0x1ffffffffff9dac9b;
  377. int256 constant c3 = 0x0aaaaaaac16877908;
  378. int256 constant c5 = 0x0666664e5e9fa0c99;
  379. int256 constant c7 = 0x049254026a7630acf;
  380. int256 constant c9 = 0x038bd75ed37753d68;
  381. int256 constant c11 = 0x03284a0c14610924f;
  382.  
  383. // The polynomial R = c1*x + c3*x^3 + ... + c11 * x^11
  384. // approximates the function log(1+x)-log(1-x)
  385. // Hence R(s) = log((1+s)/(1-s)) = log(a)
  386. function fixedLog(uint256 a) internal pure returns (int256 log) {
  387. int32 scale = 0;
  388. while (a > sqrt2) {
  389. a /= 2;
  390. scale++;
  391. }
  392. while (a <= sqrtdot5) {
  393. a *= 2;
  394. scale--;
  395. }
  396. int256 s = (((int256)(a) - one) * one) / ((int256)(a) + one);
  397. int z = (s*s) / one;
  398. return scale * ln2 +
  399. (s*(c1 + (z*(c3 + (z*(c5 + (z*(c7 + (z*(c9 + (z*c11/one))
  400. /one))/one))/one))/one))/one);
  401. }
  402.  
  403. int256 constant c2 = 0x02aaaaaaaaa015db0;
  404. int256 constant c4 = -0x000b60b60808399d1;
  405. int256 constant c6 = 0x0000455956bccdd06;
  406. int256 constant c8 = -0x000001b893ad04b3a;
  407.  
  408. // The polynomial R = 2 + c2*x^2 + c4*x^4 + ...
  409. // approximates the function x*(exp(x)+1)/(exp(x)-1)
  410. // Hence exp(x) = (R(x)+x)/(R(x)-x)
  411. function fixedExp(int256 a) internal pure returns (uint256 exp) {
  412. int256 scale = (a + (ln2_64dot5)) / ln2 - 64;
  413. a -= scale*ln2;
  414. int256 z = (a*a) / one;
  415. int256 R = ((int256)(2) * one) +
  416. (z*(c2 + (z*(c4 + (z*(c6 + (z*c8/one))/one))/one))/one);
  417. exp = (uint256) (((R + a) * one) / (R - a));
  418. if (scale >= 0)
  419. exp <<= scale;
  420. else
  421. exp >>= -scale;
  422. return exp;
  423. }
  424.  
  425. // This allows you to buy bonds by sending Ether directly to the smart contract
  426. // without including any transaction data (useful for, say, mobile wallet apps).
  427. function () payable external {
  428. // msg.value is the amount of Ether sent by the transaction.
  429. if (msg.value > 0) {
  430. fund();
  431. } else {
  432. withdraw( resolveEarnings(msg.sender) );
  433. }
  434. }
  435.  
  436. // Allow contract to accept resolve tokens
  437. event StakeResolves( address indexed addr, uint256 amountStaked, bytes _data );
  438. function tokenFallback(address from, uint value, bytes calldata _data) external{
  439. if(msg.sender == address(resolveToken) ){
  440. resolveWeight[from] += value;
  441. dissolvingResolves += value;
  442.  
  443. // Update the payout array so that the "resolve shareholder" cannot claim resolveEarnings on previous staked resolves.
  444. int payoutDiff = (int256) (earningsPerResolve * value);
  445.  
  446. // Then we update the payouts array for the "resolve shareholder" with this amount
  447. payouts[from] += payoutDiff;
  448.  
  449. emit StakeResolves(from, value, _data);
  450. }else{
  451. revert("no want");
  452. }
  453. }
  454.  
  455.  
  456. // Withdraws resolveEarnings held by the caller sending the transaction, updates
  457. // the requisite global variables, and transfers Ether back to the caller.
  458. event Withdraw( address indexed addr, uint256 earnings, uint256 dissolve );
  459. function withdraw(uint amount) public returns(uint){
  460. // Retrieve the resolveEarnings associated with the address the request came from.
  461. uint totalEarnings = resolveEarnings(msg.sender);
  462. require(amount <= totalEarnings, "the amount exceeds total earnings");
  463. uint oldWeight = resolveWeight[msg.sender];
  464. resolveWeight[msg.sender] = oldWeight * (totalEarnings - amount) / totalEarnings;
  465. uint weightDiff = oldWeight - resolveWeight[msg.sender];
  466. dissolved += weightDiff;
  467. dissolvingResolves -= weightDiff;
  468.  
  469. //something about invariance
  470. int resolvePayoutDiff = (int256) (earningsPerResolve * weightDiff);
  471.  
  472. payouts[msg.sender] += resolvePayoutDiff;
  473.  
  474. // Increase the total amount that's been paid out to maintain invariance.
  475. totalPayouts += resolvePayoutDiff;
  476. contractBalance -= amount;
  477.  
  478. // Send the resolveEarnings to the address that requested the withdraw.
  479. msg.sender.transfer(amount);
  480. emit Withdraw( msg.sender, amount, weightDiff);
  481. return weightDiff;
  482. }
  483. event PullResolves( address indexed addr, uint256 pulledResolves, uint256 forfeiture);
  484. function pullResolves(uint amount) public{
  485. require(amount <= resolveWeight[msg.sender], "that amount is too large");
  486. require(amount != dissolvingResolves, "you can't forfeit the last amount");
  487. //something about invariance
  488. uint forfeitedEarnings = amount * earningsPerResolve;
  489.  
  490. // Update the payout array so that the "resolve shareholder" cannot claim resolveEarnings on previous staked resolves.
  491.  
  492. // Then we update the payouts array for the "resolve shareholder" with this amount
  493. payouts[msg.sender] -= (int256) (earningsPerResolve * amount);
  494.  
  495. resolveWeight[msg.sender] -= amount;
  496. dissolvingResolves -= amount;
  497. // The Ether value per token is increased proportionally.
  498. earningsPerResolve += forfeitedEarnings /dissolvingResolves;
  499. resolveToken.transfer(msg.sender, amount);
  500. emit PullResolves( msg.sender, amount, forfeitedEarnings / scaleFactor);
  501. }
  502.  
  503. event BondTransfer(address from, address to, uint amount);
  504. function bondTransfer( address to, uint amount ) public{
  505. //attack someone's resolve potential by sending them some love
  506. address sender = msg.sender;
  507. uint totalBonds = hodlBonds[sender];
  508. require(amount <= totalBonds, "amount exceeds hodlBonds");
  509. uint ethSpent = avgFactor_ethSpent[sender] * amount / totalBonds;
  510. uint buyInTimeSum = avgFactor_buyInTimeSum[sender] * amount / totalBonds;
  511. avgFactor_ethSpent[sender] -= ethSpent;
  512. avgFactor_buyInTimeSum[sender] -= buyInTimeSum;
  513. hodlBonds[sender] -= amount;
  514. avgFactor_ethSpent[to] += ethSpent;
  515. avgFactor_buyInTimeSum[to] += buyInTimeSum;
  516. hodlBonds[to] += amount;
  517. emit BondTransfer(sender, to, amount);
  518. }
  519. }
  520.  
  521. contract ERC223ReceivingContract{
  522. function tokenFallback(address _from, uint _value, bytes calldata _data) external;
  523. }
  524.  
  525. contract ResolveToken{
  526. address pyramid;
  527.  
  528. constructor(address _pyramid) public{
  529. pyramid = _pyramid;
  530. }
  531.  
  532. modifier pyramidOnly{
  533. require(msg.sender == pyramid);
  534. _;
  535. }
  536.  
  537. event Transfer(
  538. address indexed from,
  539. address indexed to,
  540. uint256 amount,
  541. bytes data
  542. );
  543.  
  544. event Mint(
  545. address indexed addr,
  546. uint256 amount
  547. );
  548.  
  549. mapping(address => uint) balances;
  550. mapping(address => mapping(address => uint)) approvals;
  551.  
  552. string public name = "Resolve";
  553. string public symbol = "`r";
  554. uint8 constant public decimals = 18;
  555. uint256 private _totalSupply;
  556.  
  557. function totalSupply() public view returns (uint256) {
  558. return _totalSupply;
  559. }
  560. function mint(address _address, uint _value) public pyramidOnly(){
  561. balances[_address] += _value;
  562. _totalSupply += _value;
  563. emit Mint(_address, _value);
  564. }
  565.  
  566. // Function that is called when a user or another contract wants to transfer funds .
  567. function transfer(address _to, uint _value, bytes memory _data) public returns (bool success) {
  568. if (balanceOf(msg.sender) < _value) revert();
  569. if(isContract(_to)) {
  570. return transferToContract(_to, _value, _data);
  571. }else{
  572. return transferToAddress(_to, _value, _data);
  573. }
  574. }
  575.  
  576. // Standard function transfer similar to ERC20 transfer with no _data .
  577. // Added due to backwards compatibility reasons .
  578. function transfer(address _to, uint _value) public returns (bool success) {
  579. if (balanceOf(msg.sender) < _value) revert();
  580. //standard function transfer similar to ERC20 transfer with no _data
  581. //added due to backwards compatibility reasons
  582. bytes memory empty;
  583. if(isContract(_to)){
  584. return transferToContract(_to, _value, empty);
  585. }else{
  586. return transferToAddress(_to, _value, empty);
  587. }
  588. }
  589.  
  590. //assemble the given address bytecode. If bytecode exists then the _addr is a contract.
  591. function isContract(address _addr) public view returns (bool is_contract) {
  592. uint length;
  593. assembly {
  594. //retrieve the size of the code on target address, this needs assembly
  595. length := extcodesize(_addr)
  596. }
  597. if(length>0) {
  598. return true;
  599. }else {
  600. return false;
  601. }
  602. }
  603.  
  604. //function that is called when transaction target is an address
  605. function transferToAddress(address _to, uint _value, bytes memory _data) private returns (bool success) {
  606. moveTokens(msg.sender,_to,_value);
  607. emit Transfer(msg.sender, _to, _value, _data);
  608. return true;
  609. }
  610.  
  611. //function that is called when transaction target is a contract
  612. function transferToContract(address _to, uint _value, bytes memory _data) private returns (bool success) {
  613. moveTokens(msg.sender, _to, _value);
  614. ERC223ReceivingContract reciever = ERC223ReceivingContract(_to);
  615. reciever.tokenFallback(msg.sender, _value, _data);
  616. emit Transfer(msg.sender, _to, _value, _data);
  617. return true;
  618. }
  619.  
  620. function moveTokens(address _from, address _to, uint _amount) private{
  621. balances[_from] -= _amount;
  622. balances[_to] += _amount;
  623. }
  624.  
  625. function balanceOf(address _owner) public view returns (uint balance) {
  626. return balances[_owner];
  627. }
  628.  
  629. function allowance(address src, address guy) public view returns (uint) {
  630. return approvals[src][guy];
  631. }
  632.  
  633. function transferFrom(address src, address dst, uint wad) public returns (bool){
  634. require(approvals[src][msg.sender] >= wad, "That amount is not approved");
  635. require(balances[src] >= wad, "That amount is not available from this wallet");
  636. if (src != msg.sender) {
  637. approvals[src][msg.sender] -= wad;
  638. }
  639. moveTokens(src,dst,wad);
  640.  
  641. bytes memory empty;
  642. emit Transfer(src, dst, wad, empty);
  643.  
  644. return true;
  645. }
  646.  
  647. function approve(address guy, uint wad) public returns (bool) {
  648. approvals[msg.sender][guy] = wad;
  649.  
  650. emit Approval(msg.sender, guy, wad);
  651.  
  652. return true;
  653. }
  654.  
  655. event Approval(address indexed src, address indexed guy, uint wad);
  656. }
  657.  
  658. /**
  659. * @title SafeMath
  660. * @dev Math operations with safety checks that throw on error
  661. */
  662. library SafeMath {
  663. /**
  664. * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
  665. */
  666. function sub(uint256 a, uint256 b) internal pure returns (uint256) {
  667. assert(b <= a);
  668. return a - b;
  669. }
  670. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement