github.com/igggame/nebulas-go@v2.1.0+incompatible/nf/nvm/test/contract_accept_func_standard.js (about) 1 2 "use strict"; 3 4 var DepositeContent = function (text) { 5 if (text) { 6 var o = JSON.parse(text); 7 this.balance = new BigNumber(o.balance); 8 this.expiryHeight = new BigNumber(o.expiryHeight); 9 } else { 10 this.balance = new BigNumber(0); 11 this.expiryHeight = new BigNumber(0); 12 } 13 }; 14 15 DepositeContent.prototype = { 16 toString: function () { 17 return JSON.stringify(this); 18 } 19 }; 20 21 var BankVaultContract = function () { 22 LocalContractStorage.defineMapProperty(this, "bankVault", { 23 parse: function (text) { 24 return new DepositeContent(text); 25 }, 26 stringify: function (o) { 27 return o.toString(); 28 } 29 }); 30 }; 31 32 // save value to contract, only after height of block, users can takeout 33 BankVaultContract.prototype = { 34 init: function () { 35 //TODO: 36 }, 37 38 // enables accepting NAS via 'binary' 39 accept: function() {}, 40 41 save: function (height) { 42 var from = Blockchain.transaction.from; 43 var value = Blockchain.transaction.value; 44 var bk_height = new BigNumber(Blockchain.block.height); 45 46 var orig_deposit = this.bankVault.get(from); 47 if (orig_deposit) { 48 value = value.plus(orig_deposit.balance); 49 } 50 51 var deposit = new DepositeContent(); 52 deposit.balance = value; 53 deposit.expiryHeight = bk_height.plus(height); 54 55 this.bankVault.put(from, deposit); 56 }, 57 58 takeout: function (value) { 59 var from = Blockchain.transaction.from; 60 var bk_height = new BigNumber(Blockchain.block.height); 61 var amount = new BigNumber(value); 62 63 var deposit = this.bankVault.get(from); 64 if (!deposit) { 65 throw new Error("No deposit before."); 66 } 67 68 if (bk_height.lt(deposit.expiryHeight)) { 69 throw new Error("Can not takeout before expiryHeight."); 70 } 71 72 if (amount.gt(deposit.balance)) { 73 throw new Error("Insufficient balance."); 74 } 75 76 var result = Blockchain.transfer(from, amount); 77 if (!result) { 78 throw new Error("transfer failed."); 79 } 80 Event.Trigger("BankVault", { 81 Transfer: { 82 from: Blockchain.transaction.to, 83 to: from, 84 value: amount.toString() 85 } 86 }); 87 88 deposit.balance = deposit.balance.sub(amount); 89 this.bankVault.put(from, deposit); 90 }, 91 92 balanceOf: function () { 93 var from = Blockchain.transaction.from; 94 return this.bankVault.get(from); 95 }, 96 97 verifyAddress: function (address) { 98 // 1-valid, 0-invalid 99 var result = Blockchain.verifyAddress(address); 100 return { 101 valid: result == 0 ? false : true 102 }; 103 } 104 }; 105 106 module.exports = BankVaultContract; 107