如何在智能合约中实时更新 Matic 的价格

问题描述 投票:0回答:1

我正在开发一个智能合约,允许用户支付每月订阅费用,例如 Netflix、Amazon 等......

假设每个订阅费用为每月 20 美元,相当于撰写本文时的 22 Matic。

订阅期间,用户每月需向 Matic 支付 20 美元,其价值会有所不同。

如何更新智能合约内的每月付款,以便订阅者能够以 MATIC 的当前价值不多不少地支付每笔费用?坚固有可能吗?

或者我应该让用户根据每次订阅的价格(以美元为单位)手动每月支付订阅费用,但使用 MATIC?

我尝试在我的智能合约中与 Tellor 一起实施解决方案,但我陷入了困境。

// smart contract subscription(part of it)
struct Subscription {
        address payable subscriber;
        uint start;
        uint nextPayment;
        bool activated;
    }

    
    /* nested mapping from address to id to Subscription */ 
    mapping(address => mapping(uint => Subscription)) private AllSubscriptions;


/* Pay subscription every Month*/
    function pay(uint256 planId) 
        external payable
        onlyUsers()
        {
        Subscription storage submitSubscription = AllSubscriptions[msg.sender][planId];

        require(block.timestamp > submitSubscription.nextPayment, " Payement not due yet");
        Plan storage plan = idToPlan[planId];

        require(msg.value >= plan.monthlyPayment, " Monthly payment not correct");

        emit PaymentSent(
            payable(msg.sender),
            payable(address(this)),
            plan.monthlyPayment,
            planId,
            block.timestamp);
        totalPaymentsPerWallet[msg.sender] += 1; 
        submitSubscription.nextPayment = submitSubscription.nextPayment + 4 weeks;

    }

// UsingTellor functionalities
// SPDX-License-Identifier: GPL-3.0
  pragma solidity ^0.8.0;

  import "usingtellor/contracts/UsingTellor.sol";

  contract PriceContract is UsingTellor {

  uint256 public btcPrice;

  //This Contract now has access to all functions in UsingTellor

  constructor(address payable _tellorAddress) UsingTellor(_tellorAddress) public {}

  function setBtcPrice() public {

    bytes memory _b = abi.encode("SpotPrice",abi.encode("MATIC","USD"));
    bytes32 _queryID = keccak256(_b);

    bool _didGet;
    uint256 _timestamp;
    bytes _value;

    (_didGet, _value, _timestamp) = getDataBefore(_queryID);

    uint256 maticPrice = abi.decode(_value,(uint256));

    require(token.transferFrom(subscriber,address(this),cost/maticPrice));
  }
}
solidity go-ethereum
1个回答
1
投票

您可以使用任何能够返回 MATIC 当前美元价格的 Chainlink 数据源。这是一项免费服务,数据馈送无需 LINK 付费。

文档和代码示例:https://docs.chain.link/docs/get-the-latest-price/

© www.soinside.com 2019 - 2024. All rights reserved.