如何将 ETH 从账户钱包转移到智能合约

How can I transfer eth from an account wallet to a smart contract

我正在创建一个允许人们支付月度订阅费用的智能合约

我被堆在了这里:

如何从用户钱包转plan.amount到智能合约?

function subscribe(uint planId) external {
    Plan storage plan = plans[planId];
    require(plan.merchant != address(0), 'address not valid');

    bool sent = payable(address(this)).send(plan.amount);
        require(sent, "tx failed");
 
    emit PaymentSent(
      msg.sender, 
      plan.merchant,
      plan.amount, // the monthly amount for Subscription
      planId, 
      block.timestamp
    );


    subscriptions[msg.sender][planId] = Subscription(
      msg.sender,
      block.timestamp, 
      block.timestamp + 4 weeks // next payement
    );
    emit SubscriptionCreated(msg.sender, planId, block.timestamp);
  } 

subscribe() 函数需要使用 payable 修饰符才能接受 ETH。然后您可以在使用 msg.value 全局变量调用您的函数时验证用户发送了多少。

无法从合约中请求特定金额,因为合约代码是在用户发送交易后执行的。您始终需要验证用户在调用该函数的交易中发送了多少。

function subscribe(uint planId) external payable {
    // revert if the sent value is not expected
    require(msg.value == 1 ether, "You need to send 1 ETH");
}

但是,您可以控制 UI 上的预定义值,同时向他们的 MetaMask 或其他钱包创建交易请求。

await window.ethereum.request(
    method: 'eth_sendTransaction',
    [
        from: userAddress,
        to: yourContract,
        data: <invoking the subscribe() function>,
        value: <1 ETH in wei, in hex>
    ]
);

文档:https://docs.metamask.io/guide/ethereum-provider.html#ethereum-request-args