Liquidity Pool

Icon Link流动性池示例

在 Fuel 中,所有的合约都可以铸造和销毁自己的原生资产。合约还可以接收和转移任何原生资产,包括它们自己的资产。通过调用推送的所有原生资产或由合约铸造的原生资产的内部余额都由 FuelVM 跟踪,并且可以在任何时候使用 std 库中的 balance_of 函数查询。因此,不需要使用持久存储手动记录合约的余额。

std 库提供了便利的方法来访问 Fuel 的原生资产操作。

在这个例子中,我们展示了一个基本的流动性池合约,铸造了自己的原生资产 LP 资产。

contract;
 
use std::{
    asset::{
        mint_to,
        transfer,
    },
    call_frames::msg_asset_id,
    constants::DEFAULT_SUB_ID,
    context::msg_amount,
    hash::*,
};
 
abi LiquidityPool {
    fn deposit(recipient: Address);
    fn withdraw(recipient: Address);
}
 
const BASE_ASSET: AssetId = AssetId::from(0x9ae5b658754e096e4d681c548daf46354495a437cc61492599e33fc64dcdc30c);
 
impl LiquidityPool for Contract {
    fn deposit(recipient: Address) {
        assert(msg_asset_id() == BASE_ASSET);
        assert(msg_amount() > 0);
 
        // Mint two times the amount.
        let amount_to_mint = msg_amount() * 2;
 
        // Mint some LP assets based upon the amount of the base asset.
        mint_to(Identity::Address(recipient), DEFAULT_SUB_ID, amount_to_mint);
    }
 
    fn withdraw(recipient: Address) {
        let asset_id = AssetId::default();
        assert(msg_asset_id() == asset_id);
        assert(msg_amount() > 0);
 
        // Amount to withdraw.
        let amount_to_transfer = msg_amount() / 2;
 
        // Transfer base asset to recipient.
        transfer(Identity::Address(recipient), BASE_ASSET, amount_to_transfer);
    }
}