Conditional Redemption

Conditional On-Chain Package Redemption

As an example, we can create a wrapper contract that will only allow users to redeem a package if the price of Ethereum has reached $3,000.

We do so by using a Chainlink price oracle to fetch the last recorded price of ETH/USDC.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.15;

import "./PostOffice.sol";
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";

contract ConditionalDeliveryService {
    PostOffice public postOffice;
    AggregatorV3Interface public chainlinkAggregator;

    uint8 public constant USDC_DECIMALS = 6;
    uint256 public constant CHAINLINK_DECIMALS = 8;
    uint256 public constant TO_SCALE = 10 ** (CHAINLINK_DECIMALS - USDC_DECIMALS);
    // The target price ($3,000)
    uint256 public constant TARGET_PRICE = 3000 * 10 ** USDC_DECIMALS;

    constructor(address postOfficeAddress_, address chainlinkAggregator_) {
        postOffice = PostOffice(postOfficeAddress_);
        chainlinkAggregator = AggregatorV3Interface(chainlinkAggregator_);
    }

    function shipPackage(
        CapsuleData.CapsuleContent calldata packageContent_,
        PostOffice.SecurityInfo calldata securityInfo_,
        address receiver_
    ) external returns (uint256) {
        return postOffice.shipPackage(packageContent_, securityInfo_, receiver_);
    }

    function pickupPackageIfEthAbove3k(
        uint256 packageId_,
        string calldata rawPassword_,
        string calldata salt_,
        bool shouldRedeem_
    ) external {
        (, int256 _price, , , ) = chainlinkAggregator.latestRoundData();

        uint256 priceInUSDC = uint256(_price) / TO_SCALE;

        require(priceInUSDC >= TARGET_PRICE, "ETH price is not above 3000 USDC");
        postOffice.pickup(packageId_, rawPassword_, salt_, shouldRedeem_);
    }
}

Here's what the ConditionalDeliveryService contract does:

  • shipPackage: This function simply wraps the shipPackage function from the PostOffice.

  • redeemPackageIfEthAbove3k: This function allows a package to be redeemed only if the price of ETH is above 3000 USDC. It fetches the latest ETH/USDC pair data from a Chainlink price oracle, and then compares it with the target price. If the returned price is above 3000, the package will be redeemed.

The ConditionalDeliveryService contract allows users to create packages that can only be redeemed if the price of ETH is above a certain threshold ($3,000).

Last updated