Solidity

轉入接收方賬戶的乙太幣不准確

  • April 27, 2017

我正在嘗試在用 Solidity 編寫的智能合約中將一些乙太幣從一個帳戶發送到另一個帳戶。轉賬成功,但收到的金額與轉賬金額不完全匹配。有一個非常微小的差異,有時會增加,有時會減少。

例如 -

received amount: 0.04999999999999716
Transferred amount: 0.05

另一個例子 -

Received amount - 0.05000000000001137
Transferred amount -0.05

有什麼我想念的嗎?

進行傳輸的 Solidity 函式 -

function borrowBook(uint id) onlyMember payable{
   // Can't borrow book if passed value is not sufficient
   if (msg.value < 100){
       throw;
   }
   // Can't borrow a non-existent book
   if (id > numBooks || catalog[id].state != State.Available) {
       throw;
   }
   catalog[id].borrower = msg.sender;
   catalog[id].dateIssued = now;
   catalog[id].state = State.Borrowed;
   // 50% value is shared with the owner
   var owner_share = msg.value/2; 
   if (!catalog[id].owner.send(owner_share)){
       throw;
   }
   Borrow(id, msg.sender, catalog[id].dateIssued);
}

我正在檢查發送方和接收方餘額的測試案例 -

   it.only('should borrow book and transfer 50% weis to owner account', async function(){
       await lms.addBook('a', 'b', 'c');
       await lms.addMember('Michael Scofield', accounts[2]);
       // balance of owner and borrower's account before book borrow
       let ownerBal1 = web3.fromWei(web3.eth.getBalance(accounts[0]).valueOf());
       let borrowBal1 = web3.fromWei(web3.eth.getBalance(accounts[2]).valueOf());
       await lms.borrowBook(1, {from: accounts[2], value: web3.toWei(0.1)});
       // balance of owner and borrower's account after book borrow
       let ownerBal2 = web3.fromWei(web3.eth.getBalance(accounts[0]).valueOf());
       let borrowBal2 = web3.fromWei(web3.eth.getBalance(accounts[2]).valueOf());
       let contractBal = web3.fromWei(web3.eth.getBalance(lms.address).valueOf());
       // contract account get's 50% of the value
       assert.equal(contractBal, 0.05);
       // owner's account should get increased by approx 50% of sent value
       console.log(ownerBal2 - ownerBal1);
       console.log(0.05);
       console.log(borrowBal1-borrowBal2);
       assert.isAtMost(ownerBal2 - ownerBal1, 0.05);
       // borrower's account shoul d get decreased by atleat total sent value
       assert.isAtLeast(borrowBal1 - borrowBal2, 0.1);
   });

如果可能,將值保留在BigNumber中以避免 Javascript 精度和數量限制。盡量避免使用valueOf(),並在需要時更喜歡使用 BigNumber 方法。

所以更精確的程式碼是這樣的:

let ownerBal1 = web3.fromWei(web3.eth.getBalance(accounts[0]));

ownerBal2.sub(ownerBal1);

引用自:https://ethereum.stackexchange.com/questions/15459