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