Redeem FAssets
Overview
In this guide, you will learn how to redeem FAssets using the Asset Manager smart contract.
Redemption is the process of burning FAssets (e.g., FXRP) on Flare in exchange for their equivalent value on the original chain (e.g., XRP on XRPL).
See the Redemption overview for more details.
Prerequisites
Redeem FAssets Smart Contract
The following example demonstrates how to redeem FAssets using the AssetManager smart contract.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IAssetManager} from "@flarenetwork/flare-periphery-contracts/coston2/IAssetManager.sol";
import {AssetManagerSettings} from "@flarenetwork/flare-periphery-contracts/coston2/userInterfaces/data/AssetManagerSettings.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
contract FAssetsRedeem {
// 1. Use the AssetManager contract
IAssetManager public immutable assetManager;
IERC20 public immutable underlyingToken;
address public immutable fAssetToken;
constructor(address _assetManager, address _fAssetToken) {
assetManager = IAssetManager(_assetManager);
fAssetToken = _fAssetToken;
}
// 2. Approve FAssets for redemption
function approveFAssets(uint256 _amount) public returns (bool) {
return IERC20(fAssetToken).approve(address(this), _amount);
}
// 3. Redeem FAssets (requires prior approval)
function redeem(
uint256 _lots,
string memory _redeemerUnderlyingAddressString
) public returns (uint256) {
// Calculate the amount of FXRP needed for redemption
AssetManagerSettings.Data memory settings = assetManager.getSettings();
uint256 amountToRedeem = settings.lotSizeAMG * _lots;
// Transfer FXRP from caller to AssetManager
IERC20(fAssetToken).transferFrom(
msg.sender,
address(this),
amountToRedeem
);
uint256 redeemedAmountUBA = assetManager.redeem(
_lots,
_redeemerUnderlyingAddressString,
payable(address(0))
);
return redeemedAmountUBA;
}
// 4. Get the AssetManager settings
function getSettings()
public
view
returns (uint256 lotSizeAMG, uint256 assetDecimals)
{
AssetManagerSettings.Data memory settings = assetManager.getSettings();
lotSizeAMG = settings.lotSizeAMG;
assetDecimals = settings.assetDecimals;
return (lotSizeAMG, assetDecimals);
}
}
Code Breakdown
- Define the asset manager contract address to interact with it.
- Approve FAssets (FXRP) tokens for redemption.
- Redeem the FAssets using the
redeemfunction by specifying the number of lots to redeem and the underlying chain address. - Retrieve the asset manager settings to calculate the redeemed amount; for this, you need to obtain the
lotSizeAMGandassetDecimalsfrom the asset manager settings document.
In this example, you are not using the executor vault address, but you can use it to redeem FAssets on behalf of another address.
Deploy and Interact with the Smart Contract
To deploy the contract and redeem FAssets, you can use the Flare Hardhat Starter Kit.
Create a new file, for example, scripts/fassets/redeem.ts and add the following code:
Import the Required Contracts
At first, you need to import the required dependencies and smart contract TypeScript types:
import { ethers, web3, run } from "hardhat";
import { formatUnits } from "ethers";
import {
FAssetsRedeemInstance,
IAssetManagerContract,
ERC20Instance,
} from "../../typechain-types";
Define the Constants
Define the constants:
ASSET_MANAGER_ADDRESS- asset manager address;LOTS_TO_REDEEM- the number of lots to redeem;UNDERLYING_ADDRESS- underlying chain address where the redeemed asset will be sent;
// AssetManager address on Flare Testnet Coston2 network
const ASSET_MANAGER_ADDRESS = "0xDeD50DA9C3492Bee44560a4B35cFe0e778F41eC5";
const LOTS_TO_REDEEM = 1;
const UNDERLYING_ADDRESS = "rSHYuiEvsYsKR8uUHhBTuGP5zjRcGt4nm";
Import Contract Artifacts
Import the contract artifacts to interact with the smart contracts:
FAssetsRedeem- theFAssetsRedeemcontract;IAssetManager- the asset manager interface;IERC20- theIERC20contract for FXRP token;
const FAssetsRedeem = artifacts.require("FAssetsRedeem");
const IAssetManager = artifacts.require("IAssetManager");
const IERC20 = artifacts.require("IERC20");
Deploy and Verify the Redeem Contract
Deploy and verify the smart contract providing the asset manager address as a constructor argument:
async function deployAndVerifyContract() {
// Get FXRP address first
const fxrpAddress = await getFXRPAddress();
console.log("FXRP address:", fxrpAddress);
const args = [ASSET_MANAGER_ADDRESS, fxrpAddress];
const fAssetsRedeem: FAssetsRedeemInstance = await FAssetsRedeem.new(...args);
const fAssetsRedeemAddress = await fAssetsRedeem.address;
try {
await run("verify:verify", {
address: fAssetsRedeem.address,
constructorArguments: args,
});
} catch (e: any) {
console.log(e);
}
console.log("FAssetsRedeem deployed to:", fAssetsRedeemAddress);
return fAssetsRedeem;
}
Approve the FXRP transfer to the Redeem Contract
To redeem FAssets, you must approve a sufficient amount of transfer of FXRP to the FAssetsRedeem contract address after it is deployed, as it acts as the invoker during the redemption process.
async function approveFAssets(fAssetsRedeem: any, amountToRedeem: string) {
console.log("Approving FAssetsRedeem contract to spend FXRP...");
const fxrpAddress = await getFXRPAddress();
const fxrp: ERC20Instance = await IERC20.at(fxrpAddress);
const approveTx = await fxrp.approve(
await fAssetsRedeem.address,
amountToRedeem,
);
console.log("FXRP approval completed");
}
In a production environment, it is recommended to use a more secure method for approving the transfer of FXRP to a smart contract.
Parse the Redemption Events
During the redemption process, the AssetManager emits events:
RedemptionRequested- holds the agent vault address, redemption request id, the amount of FAssets to redeem, and other important information.RedemptionTicketCreated- holds the redemption ticket information updated during the redemption process.
To parse the redemption events, you can use the following function:
async function parseRedemptionEvents(
transactionReceipt: any,
fAssetsRedeem: any,
) {
console.log("\nParsing events...", transactionReceipt.rawLogs);
// Get AssetManager contract interface
const assetManager = (await ethers.getContractAt(
"IAssetManager",
ASSET_MANAGER_ADDRESS,
)) as IAssetManagerContract;
for (const log of transactionReceipt.rawLogs) {
try {
// Try to parse the log using the AssetManager interface
const parsedLog = assetManager.interface.parseLog({
topics: log.topics,
data: log.data,
});
if (parsedLog) {
const redemptionEvents = [
"RedemptionRequested",
"RedemptionTicketUpdated",
];
if (redemptionEvents.includes(parsedLog.name)) {
console.log(`\nEvent: ${parsedLog.name}`);
console.log("Arguments:", parsedLog.args);
}
}
} catch (e) {
console.log("Error parsing event:", e);
}
}
}
Redeeming FAssets
To put it altogether you can use the following function to deploy the contract, transfer FXRP to it, redeem the FAssets, and parse the redemption events:
async function main() {
// Deploy and verify the contract
const fAssetsRedeem = await deployAndVerifyContract();
// Get the lot size and decimals to calculate the amount to redeem
const settings = await fAssetsRedeem.getSettings();
const lotSize = settings[0];
const decimals = settings[1];
console.log("Lot size:", lotSize.toString());
console.log("Asset decimals:", decimals.toString());
// Calculate the amount to redeem according to the lot size and the number of lots to redeem
const amountToRedeem = web3.utils
.toBN(lotSize)
.mul(web3.utils.toBN(LOTS_TO_REDEEM));
console.log(
`Required FXRP amount ${formatUnits(amountToRedeem.toString(), Number(decimals))} FXRP`,
);
console.log(`Required amount in base units: ${amountToRedeem.toString()}`);
// Approve FXRP for redemption
await approveFAssets(fAssetsRedeem, amountToRedeem.toString());
// Call redeem function and wait for transaction
const redeemTx = await fAssetsRedeem.redeem(
LOTS_TO_REDEEM,
UNDERLYING_ADDRESS,
);
// const receipt = await tx.wait();
console.log("Redeem transaction receipt", redeemTx);
// // Parse events from the transaction
await parseRedemptionEvents(redeemTx.receipt, fAssetsRedeem);
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});
Run the Script
To run the script, use the Flare Hardhat Starter Kit with the following command:
npx hardhat run scripts/fassets/getLotSize.ts --network coston2
Once the script is executed, two events hold the important information:
RedemptionRequested
The RedemptionRequested event contains the agent vault address, redeemer address, underlying chain address, amount of FAssets to redeem, redemption fee, and other important information.
Event: RedemptionRequested
Arguments: Result(12) [
'0x3c831Fe4417bEFFAc721d24996985eE2dd627053',
'0xCA7C9fBbA56E44C508bcb4872775c5fEd169cDb3',
1898730n,
'rSHYuiEvsYsKR8uUHhBTuGP5zjRcGt4nm',
20000000n,
20000n,
6386165n,
6386708n,
1744293249n,
'0x46425052664100020000000000000000000000000000000000000000001cf8ea',
'0x0000000000000000000000000000000000000000',
0n
]
When decoding an event, the most important data from the event is:
- The agent vault address that will redeem the FAssets is
0x3c831Fe4417bEFFAc721d24996985eE2dd627053; - The redeemer address is
0xCA7C9fBbA56E44C508bcb4872775c5fEd169cDb3; - The redemption ticket id is
1898730; - The underlying chain address is
rSHYuiEvsYsKR8uUHhBTuGP5zjRcGt4nm; - The amount of FAssets to redeem is
20000000; - The redemption fee is
20000;
You can view the full event description here.
RedemptionTicketUpdated
The event RedemptionTicketUpdated contains the redemption ticket information, including the agent vault address, redemption ticket ID, and the value of the redemption ticket in the underlying chain currency.
For every minting, a redemption ticket is created, and during the redemption process, the redemption ticket is updated with the new redemption status.
Event: RedemptionTicketUpdated
Arguments: Result(3) [
'0x3c831Fe4417bEFFAc721d24996985eE2dd627053',
870n,
3440000000n
]
Once decoding the most important data from the event is:
- The agent vault address that will redeem the FAssets is
0x3c831Fe4417bEFFAc721d24996985eE2dd627053; - The redemption ticket id is
870; - The value of the redemption ticket in underlying chain currency is
3440000000(partially redeemed).
You can read the full event description here.
Agent Process
The FAssets agent should perform the redemption, and the user must retrieve the redeemed assets from the agent.
If the agent is unable to redeem the assets on the underlying chain in the specified time.
In that case, the user can execute the redemptionPaymentDefault function to receive compensation from the agent's collateral.
If the agent rejects the redemption request and no other agent takes over the redemption, the redeemer or appointed executor calls rejectedRedemptionPaymentDefault method and receives payment in collateral.
The agent can also call default if the redeemer is unresponsive to payout the redeemer and free the remaining collateral.
Next Steps
This is only the first step of the redemption process. The redeemer or agent completes the redemption process when proof of payment is presented to the FAssets system. Read more about the redemption process in the here.