Introduction
Hi, I'm cardene, a software engineer and technical writer focused on blockchain and AI.
I've also authored Japanese technical books on specification-driven development with LLMs and decentralized application (DApp) development.
I also build and publish a variety of tools, libraries, and open-source projects.
This article examines ERC7527, a proposal for wrapping and unwrapping ERC20 tokens or ETH as ERC721 tokens (NFTs) using a Function Oracle Automated Market Maker (FOAMM) to automate pricing and improve liquidity.
The following sections translate, summarize, and expand on the proposal below.
I also cover a range of other EIPs.
Overview
This standard proposes an interface for converting ERC20 tokens or ETH into ERC721 tokens and a system for performing the reverse conversion.
What are ERC tokens?
First, let's briefly review what ERC tokens are.
- ERC20
- The most commonly used fungible token standard on Ethereum.
- Mainly used to represent divisible value or rights, such as currency or voting rights.
- ERC-721
- A standard for creating non-fungible tokens (NFTs), each of which has a unique identity.
- Mainly used when individual items have distinct value, such as digital art and collectibles.
For more about ERC20, see the following article.
For more about ERC721, see the following article.
Overview of the proposal
The proposal aims to provide interfaces for wrapping ERC20 tokens or ETH into ERC721 tokens and unwrapping ERC721 tokens back into ERC20 tokens or ETH. In other words, tokens representing a particular value can be converted into unique NFTs, and the conversion can be reversed.
Function Oracle Automated Market Maker (FOAMM)
An important feature is the Function Oracle Automated Market Maker (FOAMM), which determines the prices used when minting or burning NFTs. It is an oracle mechanism that provides prices based on embedded equations and is used to execute and settle NFT minting and burning.
Why does this matter?
The idea behind the proposal is to bridge liquid tokens and NFTs representing unique value. For example, someone holding a particular ERC20 token could use this system to convert it into a unique NFT, such as an art-related token. The reverse conversion is also possible.
Technical implementation challenges
Implementation involves several technical challenges to ensure security, efficiency, and usability. Examples include the accuracy of FOAMM pricing, the security of the conversion process between ERC20 and ERC721, and the usability of the user interface.
If implemented successfully, this proposal could expand the liquidity and diversity of Ethereum assets and enable new types of token economies.
Motivation
The proposed Function Oracle Automated Market Maker (FOAMM) system is designed to address liquidity challenges in decentralized systems, particularly for unique assets and tokens with low trading volumes, such as NFTs. The objective is to provide liquidity for NFTs and an automated pricing solution while preserving transparency through smart contracts.
Automated price discovery
In a FOAMM system, transactions do not require a matching counterparty. When interacting directly with the pool, the FOAMM automatically obtains a price from an oracle using predefined functions. This automates NFT price discovery and allows users who wish to buy or sell NFTs to transact without finding a direct counterparty in the market.
Automated price discovery is the mechanism by which the FOAMM system automatically determines prices for NFT transactions. Conventional market transactions require a buyer and a seller, but the FOAMM system automates this process, eliminating the need to find a matching counterparty. The oracle plays an important role here. An oracle supplies pricing information based on external information sources or predefined rules.
The FOAMM automated price discovery process
Pricing
When a user wraps assets (converting ERC20 tokens or ETH into an NFT) or unwraps an NFT (converting it back into ERC20 tokens or ETH), the FOAMM uses an oracle. This oracle calculates the current price using predefined mathematical functions.
Automation With this system, users do not need to find another person and negotiate a price whenever they want to transact. The FOAMM's price is automatically determined by the oracle, allowing users to transact immediately at that price.
Transparency and efficiency Prices are transparent to all participants. Because transactions do not require human intervention, they can be processed more quickly and efficiently.
Example
Suppose an artist wants to sell an NFT representing a piece of digital art. In a conventional market, the artist must set a suitable price and find a prospective buyer. With a FOAMM-based system, the artist could instead deposit the NFT into a supporting platform, which automatically determines its price, allowing prospective buyers to purchase it at that price. This illustrates a potential application rather than an interface requirement.
FOAMM's automated price discovery is therefore intended to improve NFT market liquidity and reduce barriers to trading, making NFT transactions more accessible.
Improved liquidity
In conventional decentralized exchange (DEX) models, liquidity providers (LPs) deposit tokens into liquidity pools to facilitate trading and supply liquidity. When these LPs withdraw, the liquidity available in the market can fluctuate significantly, potentially causing instability.
In the FOAMM system, liquidity is added or removed internally through wrap and unwrap, rather than relying on external LPs. This reduces instability caused by sudden LP withdrawals and allows liquidity to be continuously replenished and maintained through ongoing participant interactions.
The motivation behind FOAMM is to bring greater reliability to the NFT ecosystem. By automating price discovery and improving liquidity, it aims to address several major NFT market challenges and promote more efficient and transparent transactions. These innovations are expected to make trading NFTs and other unique assets more accessible and secure.
Specification
The proposed contract interfaces comprise three main components: Agency, App, and Factory. These interfaces manage the process of wrapping ERC20 tokens or ETH into ERC721 tokens and performing the reverse unwrapping operation. The main objective is to automate price discovery and improve liquidity when converting tokens or ETH into unique NFTs.
Roles of Agency and App
Agency and App may be implemented by the same contract or by separate contracts. When implemented separately, they are bound to each other so that the binding cannot be upgraded after initialization. The App contract implements an onlyAgency() modifier so that minting and burning are effective only when invoked through the corresponding Agency. In other words, the App's minting and burning functionality is controlled through the Agency. Implementing onlyApp() in the Agency is optional. It is useful when an operation should only be callable by the App.
Factory interface
The Factory interface is optional and is particularly useful when Agency and App instances must be deployed repeatedly. The factory pattern makes it easy to create and manage Agency and App instances.
Implementing the Function Oracle
The Function Oracle is implemented through getWrapOracle and getUnwrapOracle, which provide prices based on parameters and mathematical equations defined by their implementations. This automatically determines prices for wrapping and unwrapping.
Implementing FOAMM
wrap and unwrap call getWrapOracle and getUnwrapOracle to obtain prices and automatically settle transactions.
To execute a wrap, the FOAMM receives the premium and initiates mint in the App.
To execute an unwrap, the FOAMM pays out the premium and initiates burn in the App.
- The Agency acts as a single entry point for all transfers associated with minting and burning.
Premium
A premium is the amount associated with performing an action, such as wrapping or unwrapping a token. In ERC7527, distinguish the premium or quoted asset price from the separate fee charged for the conversion.
Purpose of the premium
Price adjustment The premium plays a role in adjusting prices based on market supply and demand. For low-liquidity or highly demanded items, the pricing function can reflect their value through the premium.
Providing incentives The pricing and fee mechanism can provide incentives for those contributing to system maintenance and development. For example, a portion of the amount collected during wrapping may be allocated as a fee to system operators or developers, supporting ongoing improvements and stable operation.
Risk management The premium can also be used to account for risks in the conversion process, such as price fluctuations. Because token conversions are exposed to changes in market prices, the pricing mechanism can absorb some of this risk.
Calculating the premium
The specific premium depends on system design and market conditions. It is generally calculated automatically using mathematical functions defined in the FOAMM system and used to determine the price applicable to wrapping or unwrapping.
Example
Suppose a user wants to wrap ETH into a particular NFT. The process requires the premium quoted for the conversion and any separate applicable fee. The fee may compensate for the convenience, speed, or other added value of the conversion service.
This design enables NFT minting and burning to proceed smoothly without external intervention or a matching counterparty. Through FOAMM, it also aims to address liquidity challenges and automate price discovery and stabilization in the NFT market.
Specification
Agency interface
pragma solidity ^0.8.20;
/**
* @dev The settings of the agency.
* @param currency The address of the currency. If `currency` is 0, the currency is Ether.
* @param premium The base premium of the currency.
* @param feeRecipient The address of the fee recipient.
* @param mintFeePercent The fee of minting.
* @param burnFeePercent The fee of burning.
*/
struct Asset {
address currency;
uint256 premium;
address feeRecipient;
uint16 mintFeePercent;
uint16 burnFeePercent;
}
interface IERC7527Agency {
/**
* @dev Allows the account to receive Ether
*
* Accounts MUST implement a `receive` function.
*
* Accounts MAY perform arbitrary logic to restrict conditions
* under which Ether can be received.
*/
receive() external payable;
/**
* @dev Emitted when `tokenId` token is wrapped.
* @param to The address of the recipient of the newly created non-fungible token.
* @param tokenId The identifier of the newly created non-fungible token.
* @param price The price of wrapping.
* @param fee The fee of wrapping.
*/
event Wrap(address indexed to, uint256 indexed tokenId, uint256 price, uint256 fee);
/**
* @dev Emitted when `tokenId` token is unwrapped.
* @param to The address of the recipient of the currency.
* @param tokenId The identifier of the non-fungible token to unwrap.
* @param price The price of unwrapping.
* @param fee The fee of unwrapping.
*/
event Unwrap(address indexed to, uint256 indexed tokenId, uint256 price, uint256 fee);
/**
* @dev Wrap currency premium into a non-fungible token.
* @param to The address of the recipient of the newly created non-fungible token.
* @param data The data to encode into ifself and the newly created non-fungible token.
* @return The identifier of the newly created non-fungible token.
*/
function wrap(address to, bytes calldata data) external payable returns (uint256);
/**
* @dev Unwrap a non-fungible token into currency premium.
* @param to The address of the recipient of the currency.
* @param tokenId The identifier of the non-fungible token to unwrap.
* @param data The data to encode into ifself and the non-fungible token with identifier `tokenId`.
*/
function unwrap(address to, uint256 tokenId, bytes calldata data) external payable;
/**
* @dev Returns the strategy of the agency.
* @return app The address of the app.
* @return asset The asset of the agency.
* @return attributeData The attributeData of the agency.
*/
function getStrategy() external view returns (address app, Asset memory asset, bytes memory attributeData);
/**
* @dev Returns the price and fee of unwrapping.
* @param data The data to encode to calculate the price and fee of unwrapping.
* @return price The price of wrapping.
* @return fee The fee of wrapping.
*/
function getUnwrapOracle(bytes memory data) external view returns (uint256 price, uint256 fee);
/**
* @dev Returns the price and fee of wrapping.
* @param data The data to encode to calculate the price and fee of wrapping.
* @return price The price of wrapping.
* @return fee The fee of wrapping.
*/
function getWrapOracle(bytes memory data) external view returns (uint256 price, uint256 fee);
}Wrap
event Wrap(address indexed to, uint256 indexed tokenId, uint256 price, uint256 fee);Overview
Emitted when a token is wrapped.
Details
This event records information on-chain when ERC20 tokens or ETH are converted into ERC721 tokens. It indicates completion of the wrap and allows participants to track the transaction details.
Parameters
to- Address of the recipient of the newly created non-fungible token.
tokenId- Identifier of the newly created non-fungible token.
price- Wrapping price.
fee- Wrapping fee.
Unwrap
event Unwrap(address indexed to, uint256 indexed tokenId, uint256 price, uint256 fee);Overview
Emitted when a token is unwrapped.
Details
This event records information on-chain when an ERC721 token is converted back into ERC20 tokens or ETH. It indicates completion of the unwrap and allows participants to track the transaction details.
Parameters
to- Address of the currency recipient.
tokenId- Identifier of the non-fungible token being unwrapped.
price- Unwrapping price.
fee- Unwrapping fee.
wrap
function wrap(address to, bytes calldata data) external payable returns (uint256);Overview
Wraps currency into a non-fungible token.
Details
This function converts currency (such as ERC20 tokens or ETH) into a newly created ERC721 non-fungible token. It is also possible to encode specific data for the conversion.
Arguments
to- Address of the recipient of the newly created non-fungible token.
data- Data to encode for the non-fungible token.
Return value(s)
- Identifier of the newly created non-fungible token.
unwrap
function unwrap(address to, uint256 tokenId, bytes calldata data) external payable;Overview
Unwraps a non-fungible token into currency.
Details
This function converts a particular ERC721 non-fungible token back into the underlying currency, such as ERC20 tokens or ETH. Specific data may be supplied during unwrapping to encode information related to the token or process.
Arguments
to- Address of the currency recipient.
tokenId- Identifier of the non-fungible token to unwrap.
data- Data associated with the unwrapping process.
getStrategy
function getStrategy() external view returns (address app, Asset memory asset, bytes memory attributeData);Overview
Retrieves Agency information.
Details
This function provides information associated with the Agency. Specifically, it returns the associated App address, asset configuration, and other attribute data.
Return value(s)
app- App address.
asset- Asset configuration.
attributeData- Attribute data.
getUnwrapOracle
function getUnwrapOracle(bytes memory data) external view returns (uint256 price, uint256 fee);Overview
Returns the unwrapping price and fee.
Details
This function calculates and provides the price and fee applicable to an unwrap operation. The calculation is based on the specified data.
Arguments
data- Data used to calculate the unwrapping price and fee.
Return value(s)
price- Unwrapping price.
fee- Unwrapping fee.
getWrapOracle
function getWrapOracle(bytes memory data) external view returns (uint256 price, uint256 fee);Overview
Returns the wrapping price and fee.
Details
This function calculates and provides the price and fee applicable to a wrap operation. The calculation is based on the specified data.
Arguments
data- Data used to calculate the wrapping price and fee.
Return value(s)
price- Wrapping price.
fee- Wrapping fee.
App interface
ERC7527App must inherit the ERC721Metadata interface.
pragma solidity ^0.8.20;
interface IERC7527App {
/**
* @dev Returns the maximum supply of the non-fungible token.
*/
function getMaxSupply() external view returns (uint256);
/**
* @dev Returns the name of the non-fungible token with identifier `id`.
* @param id The identifier of the non-fungible token.
*/
function getName(uint256 id) external view returns (string memory);
/**
* @dev Returns the agency of the non-fungible token.
*/
function getAgency() external view returns (address payable);
/**
* @dev Sets the agency of the non-fungible token.
* @param agency The agency of the non-fungible token.
*/
function setAgency(address payable agency) external;
/**
* @dev Mints a non-fungible token to `to`.
* @param to The address of the recipient of the newly created non-fungible token.
* @param data The data to encode into the newly created non-fungible token.
*/
function mint(address to, bytes calldata data) external returns (uint256);
/**
* @dev Burns a non-fungible token with identifier `tokenId`.
* @param tokenId The identifier of the non-fungible token to burn.
* @param data The data to encode into the non-fungible token with identifier `tokenId`.
*/
function burn(uint256 tokenId, bytes calldata data) external;
}The token ID can be specified in the data parameter of mint.
getMaxSupply
function getMaxSupply() external view returns (uint256);Overview
Returns the maximum supply of non-fungible tokens.
Details
This function retrieves the maximum supply of non-fungible tokens defined by the contract. It indicates the upper limit on the number of tokens that can be minted.
Return value(s)
- Maximum supply.
getName
function getName(uint256 id) external view returns (string memory);Overview
Returns the name of a specific non-fungible token.
Details
Retrieves the name of the non-fungible token with the specified identifier (id).
Each token can have a unique name, and this function makes that name available.
Arguments
id- Identifier of the non-fungible token.
Return value(s)
- Token name.
getAgency
function getAgency() external view returns (address payable);Overview
Returns the Agency associated with the non-fungible token.
Details
Retrieves the address of the Agency associated with the non-fungible token. The Agency may contain functionality for managing and operating on tokens.
Return value(s)
- Agency address.
setAgency
function setAgency(address payable agency) external;Overview
Sets the Agency associated with the non-fungible token.
Details
Sets the specified address as the Agency. This establishes the Agency responsible for managing the token, subject to the binding and initialization restrictions described above.
Arguments
agency- Address of the Agency to set.
mint
function mint(address to, bytes calldata data) external returns (uint256);Overview
Mints a new non-fungible token.
Details
Mints a new non-fungible token to the specified address. Data associated with the token can be encoded when it is minted.
Arguments
to- Address of the recipient of the non-fungible token.
data- Data to encode for the token.
Return value(s)
- Identifier of the newly minted token.
burn
function burn(uint256 tokenId, bytes calldata data) external;Overview
Burns a non-fungible token.
Details
Burns the non-fungible token with the specified identifier (tokenId).
When burning, data associated with the token or process can be encoded.
Arguments
tokenId- Identifier of the non-fungible token to burn.
data- Data associated with the token.
Factory interface
If a factory is needed to deploy a bound App and Agency, it must implement the following interface.
pragma solidity ^0.8.20;
import {Asset} from "./IERC7527Agency.sol";
/**
* @dev The settings of the agency.
* @param implementation The address of the agency implementation.
* @param asset The parameter of asset of the agency.
* @param immutableData The immutable data are stored in the code region of the created proxy contract of agencyImplementation.
* @param initData If init data is not empty, calls proxy contract of agencyImplementation with this data.
*/
struct AgencySettings {
address payable implementation;
Asset asset;
bytes immutableData;
bytes initData;
}
/**
* @dev The settings of the app.
* @param implementation The address of the app implementation.
* @param immutableData The immutable data are stored in the code region of the created proxy contract of appImplementation.
* @param initData If init data is not empty, calls proxy contract of appImplementation with this data.
*/
struct AppSettings {
address implementation;
bytes immutableData;
bytes initData;
}
interface IERC7527Factory {
/**
* @dev Deploys a new agency and app clone and initializes both.
* @param agencySettings The settings of the agency.
* @param appSettings The settings of the app.
* @param data The data is additional data, it has no specified format and it is sent in call to `factory`.
* @return appInstance The address of the created proxy contract of appImplementation.
* @return agencyInstance The address of the created proxy contract of agencyImplementation.
*/
function deployWrap(AgencySettings calldata agencySettings, AppSettings calldata appSettings, bytes calldata data)
external
returns (address, address);
}AgencySettings
struct AgencySettings {
address payable implementation;
Asset asset;
bytes immutableData;
bytes initData;
}Overview
A struct defining Agency settings.
Details
This struct stores configuration related to the Agency implementation. It includes the Agency implementation address, asset parameters, immutable data, and initialization data. Immutable data is stored in the proxy contract's code region. If the initialization data is nonempty, initialization is invoked through the proxy contract.
Parameters
implementation- Address of the Agency implementation.
asset- Agency asset parameters.
immutableData- Immutable data stored in the proxy contract's code region.
initData- Initialization data.
- If nonempty, it is invoked through the proxy contract.
AppSettings
struct AppSettings {
address implementation;
bytes immutableData;
bytes initData;
}Overview
A struct defining App settings.
Details
This struct stores configuration related to the App implementation. It includes the App implementation address, immutable data, and initialization data. Immutable data is stored in the proxy contract's code region. If the initialization data is nonempty, initialization is invoked through the proxy contract.
Parameters
implementation- Address of the App implementation.
immutableData- Immutable data stored in the proxy contract's code region.
initData- Initialization data.
- If nonempty, it is invoked through the proxy contract.
deployWrap
function deployWrap(AgencySettings calldata agencySettings, AppSettings calldata appSettings, bytes calldata data)
external
returns (address, address);Overview
Deploys new Agency and App clones and initializes both.
Details
This function receives the Agency and App settings, then deploys and initializes new proxy contracts based on them. Additional data is used in the factory call and does not require a particular format. The process creates new App and Agency instances and returns their addresses.
Arguments
agencySettings- Agency settings.
- Uses the
AgencySettingsstruct.
appSettings- App settings.
- Uses the
AppSettingsstruct.
data- Additional data.
- No specific format is required; it is passed to the factory call.
Return value(s)
appInstance- Address of the created proxy for the App implementation.
agencyInstance- Address of the created proxy for the Agency implementation.
Additional considerations
The proposal includes the IERC5679Ext721 interface, which extends the existing ERC721 standard with consistent minting and burning functionality.
Previous interfaces
ERC5679 proposes the IERC5679Ext721 interface to extend minting and burning consistently.
For backward compatibility, considering that some contracts do not implement ERC721TokenReceiver, IERC7527App uses mint instead of safeMint.
The proposal states that the burn operation must respect the bound Agency relationship to ensure security and the uniqueness of the binding.
Mutual binding
Contracts implementing IERC7527App and IERC7527Agency are designed to be mutually and exclusively bound to each other. During wrapping, the received premium in fungible tokens is checked, after which the App mints a non-fungible token. Only the non-fungible token's owner or an approved party can unwrap it.
Implementation diversity
When implementing Agency and App interfaces, users can customize their functionality and fee rates. Different Agency implementations may have different wrap and unwrap logic and different oracle functions. Different App implementations support a variety of use cases.
Currency type
The currency in IERC7527Agency identifies the underlying fungible asset. Only one currency type can be defined as the fungible asset for a particular Agency. Supported currency types include ETH and various ERC20 tokens.
Token IDs
Each wrap should generate a unique token ID. This token ID is essential for verification during unwrapping and serves as a unique proof of the token. This mechanism helps protect assets held by the contract.
The discussion above focuses on wrapping and minting, and unwrapping and burning, through new Ethereum NFT interfaces, especially IERC7527App and IERC7527Agency. The following sections explain the key points in more detail.
Wrapping and minting
Strategy configuration
When implementing the Agency interface, the strategy is configured so that it cannot be upgraded after deployment.
Executing the wrap function
When wrapping, the predefined strategy parameters are passed to getWrapOracle to obtain the current premium and fee.
The corresponding premium is transferred to the Agency instance, and the fee determined by mintFeePercent is transferred to the fee recipient (feeRecipient).
The App then mints the NFT to the user's address.
Handling the premium
The premium transferred to the Agency can only be moved through the unwrap process. Executing a wrap is the only trigger for minting.
Unwrapping and burning
When unwrapping, the predefined strategy parameters are passed to getUnwrapOracle to retrieve the current premium and fee.
The App burns the NFT.
The corresponding premium, less the fee calculated using burnFeePercent, is transferred to the user's address, while the fee is transferred to the fee recipient.
Executing an unwrap is the only trigger for burning.
Combining the two interfaces
IERC7527App and IERC7527Agency can be implemented together to improve security, while implementing them independently before initialization provides flexibility.
Pricing
Retrieving prices
getWrapOracle and getUnwrapOracle are used to retrieve the current premium and fee.
They implement on-chain price retrieval through oracle functions.
They can also be called by other contracts, such as lending contracts, to obtain the premium and fee outside the wrap and unwrap process.
Function oracle
Function oracles based on on-chain and off-chain parameters are supported, but on-chain parameters are recommended for actual on-chain settlement.
The proposal focuses on increasing NFT liquidity and automating transactions. Customizable fees and strategies allow it to support various use cases.
Implementation
pragma solidity ^0.8.20;
import {
ERC721Enumerable,
ERC721,
IERC721Enumerable
} from "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {ClonesWithImmutableArgs} from "clones-with-immutable-args/ClonesWithImmutableArgs.sol";
import {IERC7527App} from "./interfaces/IERC7527App.sol";
import {IERC7527Agency, Asset} from "./interfaces/IERC7527Agency.sol";
import {IERC7527Factory, AgencySettings, AppSettings} from "./interfaces/IERC7527Factory.sol";
contract ERC7527Agency is IERC7527Agency {
using Address for address payable;
receive() external payable {}
function unwrap(address to, uint256 tokenId, bytes calldata data) external payable override {
(address _app, Asset memory _asset,) = getStrategy();
require(_isApprovedOrOwner(_app, msg.sender, tokenId), "LnModule: not owner");
IERC7527App(_app).burn(tokenId, data);
uint256 _sold = IERC721Enumerable(_app).totalSupply();
(uint256 premium, uint256 burnFee) = getUnwrapOracle(abi.encode(_sold));
_transfer(address(0), payable(to), premium - burnFee);
_transfer(address(0), _asset.feeRecipient, burnFee);
emit Unwrap(to, tokenId, premium, burnFee);
}
function wrap(address to, bytes calldata data) external payable override returns (uint256) {
(address _app, Asset memory _asset,) = getStrategy();
uint256 _sold = IERC721Enumerable(_app).totalSupply();
(uint256 premium, uint256 mintFee) = getWrapOracle(abi.encode(_sold));
require(msg.value >= premium + mintFee, "ERC7527Agency: insufficient funds");
_transfer(address(0), _asset.feeRecipient, mintFee);
if (msg.value > premium + mintFee) {
_transfer(address(0), payable(msg.sender), msg.value - premium - mintFee);
}
uint256 id_ = IERC7527App(_app).mint(to, data);
require(_sold + 1 == IERC721Enumerable(_app).totalSupply(), "ERC7527Agency: Reentrancy");
emit Wrap(to, id_, premium, mintFee);
return id_;
}
function getStrategy() public pure override returns (address app, Asset memory asset, bytes memory attributeData) {
uint256 offset = _getImmutableArgsOffset();
address currency;
uint256 premium;
address payable awardFeeRecipient;
uint16 mintFeePercent;
uint16 burnFeePercent;
assembly {
app := shr(0x60, calldataload(add(offset, 0)))
currency := shr(0x60, calldataload(add(offset, 20)))
premium := calldataload(add(offset, 40))
awardFeeRecipient := shr(0x60, calldataload(add(offset, 72)))
mintFeePercent := shr(0xf0, calldataload(add(offset, 92)))
burnFeePercent := shr(0xf0, calldataload(add(offset, 94)))
}
asset = Asset(currency, premium, awardFeeRecipient, mintFeePercent, burnFeePercent);
attributeData = "";
}
function getUnwrapOracle(bytes memory data) public pure override returns (uint256 premium, uint256 fee) {
uint256 input = abi.decode(data, (uint256));
(, Asset memory _asset,) = getStrategy();
premium = _asset.premium + input * _asset.premium / 100;
fee = premium * _asset.burnFeePercent / 10000;
}
function getWrapOracle(bytes memory data) public pure override returns (uint256 premium, uint256 fee) {
uint256 input = abi.decode(data, (uint256));
(, Asset memory _asset,) = getStrategy();
premium = _asset.premium + input * _asset.premium / 100;
fee = premium * _asset.mintFeePercent / 10000;
}
function _transfer(address currency, address recipient, uint256 premium) internal {
if (currency == address(0)) {
payable(recipient).sendValue(premium);
} else {
IERC20(currency).transfer(recipient, premium);
}
}
function _isApprovedOrOwner(address app, address spender, uint256 tokenId) internal view virtual returns (bool) {
IERC721Enumerable _app = IERC721Enumerable(app);
address _owner = _app.ownerOf(tokenId);
return (spender == _owner || _app.isApprovedForAll(_owner, spender) || _app.getApproved(tokenId) == spender);
}
/// @return offset The offset of the packed immutable args in calldata
function _getImmutableArgsOffset() internal pure returns (uint256 offset) {
// solhint-disable-next-line no-inline-assembly
assembly {
offset := sub(calldatasize(), add(shr(240, calldataload(sub(calldatasize(), 2))), 2))
}
}
}
contract ERC7527App is ERC721Enumerable, IERC7527App {
constructor() ERC721("ERC7527App", "EA") {}
address payable private _oracle;
modifier onlyAgency() {
require(msg.sender == _getAgency(), "only agency");
_;
}
function getName(uint256) external pure returns (string memory) {
return "App";
}
function getMaxSupply() public pure override returns (uint256) {
return 100;
}
function getAgency() external view override returns (address payable) {
return _getAgency();
}
function setAgency(address payable oracle) external override {
require(_getAgency() == address(0), "already set");
_oracle = oracle;
}
function mint(address to, bytes calldata data) external override onlyAgency returns (uint256 tokenId) {
require(totalSupply() < getMaxSupply(), "max supply reached");
tokenId = abi.decode(data, (uint256));
_mint(to, tokenId);
}
function burn(uint256 tokenId, bytes calldata) external override onlyAgency {
_burn(tokenId);
}
function _getAgency() internal view returns (address payable) {
return _oracle;
}
}
contract ERC7527Factory is IERC7527Factory {
using ClonesWithImmutableArgs for address;
function deployWrap(AgencySettings calldata agencySettings, AppSettings calldata appSettings, bytes calldata)
external
override
returns (address appInstance, address agencyInstance)
{
appInstance = appSettings.implementation.clone(appSettings.immutableData);
{
agencyInstance = address(agencySettings.implementation).clone(
abi.encodePacked(
appInstance,
agencySettings.asset.currency,
agencySettings.asset.premium,
agencySettings.asset.feeRecipient,
agencySettings.asset.mintFeePercent,
agencySettings.asset.burnFeePercent,
agencySettings.immutableData
)
);
}
IERC7527App(appInstance).setAgency(payable(agencyInstance));
if (agencySettings.initData.length != 0) {
(bool success, bytes memory result) = agencyInstance.call(agencySettings.initData);
if (!success) {
assembly {
revert(add(result, 32), mload(result))
}
}
}
if (appSettings.initData.length != 0) {
(bool success, bytes memory result) = appInstance.call(appSettings.initData);
if (!success) {
assembly {
revert(add(result, 32), mload(result))
}
}
}
}
}Security
Fraud prevention
To ensure contract security, the following points must be considered.
Checking modifier implementation and application
Verify that the onlyAgency() and onlyApp() modifiers are implemented and applied correctly where required.
These modifiers ensure that functions can only be called by the specified Agency or App, preventing unauthorized access and operations.
Checking function strategies
Verify that contract functions follow the appropriate strategy. This is important to ensure that the contract follows the intended business logic.
Checking for reentrancy attacks
Verify that the contract is not vulnerable to reentrancy attacks. Reentrancy can occur when an external contract interrupts an executing function by calling back into the same contract before the original execution has finished. To prevent this, update internal state before untrusted external calls where appropriate (checks-effects-interactions), or use a reentrancy prevention mechanism such as a lock.
Checking that all non-fungible tokens can be unwrapped at the premium calculated by FOAMM
Verify that all non-fungible tokens can be unwrapped using the premium calculated by the FOAMM (Function Oracle Automated Market Maker). This is important for ensuring the accuracy of premium calculations and fairness of the unwrap process.
References
Elaine Zhang (@lanyinzly) lz8aj@virginia.edu, Jerry jerrymindflow@gmail.com, Amandafanny amandafanny200@gmail.com, Shouhao Wong (@wangshouh) wongshouhao@outlook.com, 0xPoet 0xpoets@gmail.com, "ERC-7527: Token Bound Function Oracle AMM [DRAFT]," Ethereum Improvement Proposals, no. 7527, September 2023. [Online serial]. Available: https://eips.ethereum.org/EIPS/eip-7527.
Conclusion
This article covered ERC7527, which proposes wrapping and unwrapping ERC20 tokens or ETH as ERC721 tokens (NFTs) using a Function Oracle Automated Market Maker (FOAMM) to automate pricing and improve liquidity. I hope you found it useful.

