繁体   English   中英

如何在智能合约中存储 ETH?

[英]How to store ETH in the Smart Contract?

我正在编写一个 LibraryPortal 智能合约,其中多个用户可以互相租借书籍。 所以,在这个合约中, msg.value包含总金额,它是保证金和租金的组合。

我要做的是立即将租赁金额转给书的所有者并将剩余金额存储在合同中,即保证金。

如果承租人未在指定时间内归还图书,则保证金将转移给图书所有者,否则将退还给承租人。

这是我的片段:

function borrowBook(string _bName) payable returns (string){
    if(msg.sender != books[_bName].owner){
        if(books[_bName].available == true){
            if(getBalance()>=(books[_bName].amtSecurity + books[_bName].rate) ){
                books[_bName].borrower = msg.sender;
                books[_bName].available = false;
                books[_bName].owner.transfer(msg.value - books[_bName].amtSecurity);
                //  Code missing
                //  For storing
                //  ETH into the Contact
                return "Borrowed Succesful";
            }else{
                return "Insufficient Fund";
            }
        }else{
            return "Currently this Book is Not Available!";
        }
    }else{
        return "You cannot Borrow your own Book";
    }
}

您可以通过称为托管合同的方式实现结果。
以下是open-zeppelin对 Escrow 合约的实现:

contract Escrow is Secondary {
  using SafeMath for uint256;

  event Deposited(address indexed payee, uint256 weiAmount);
  event Withdrawn(address indexed payee, uint256 weiAmount);

  mapping(address => uint256) private _deposits;

  function depositsOf(address payee) public view returns (uint256) {
    return _deposits[payee];
  }

  /**
  * @dev Stores the sent amount as credit to be withdrawn.
  * @param payee The destination address of the funds.
  */
  function deposit(address payee) public onlyPrimary payable {
    uint256 amount = msg.value;
    _deposits[payee] = _deposits[payee].add(amount);

    emit Deposited(payee, amount);
  }

  /**
  * @dev Withdraw accumulated balance for a payee.
  * @param payee The address whose funds will be withdrawn and transferred to.
  */
  function withdraw(address payee) public onlyPrimary {
    uint256 payment = _deposits[payee];

    _deposits[payee] = 0;

    payee.transfer(payment);

    emit Withdrawn(payee, payment);
  }
}

您可以在合约中实例化合约并将资金转发到合约。

要完全实现类似的功能,请查看可退款的众筹合同

谢谢你们的回答,但后来我知道随交易发送到合约的 VALUE 存储在合约本身中,您可以使用address(this).balance访问它,该address(this).balance将始终为您提供该合同实例中的可用余额。 因此,您不需要任何变量或其他东西来在您的合约中存储 ETHER。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM