@glue-finance/expansions-pack
Version:
Glue Protocol Expansions Pack - Smart contract interfaces and base contracts for building with the Glue Protocol
570 lines (424 loc) โข 18.2 kB
Markdown
# Glue Protocol Expansions Pack
[](https://badge.fury.io/js/@glue-finance/expansions-pack)
[](https://github.com/glue-finance/glue-expansionspack/blob/main/LICENSE)
**Build on Glue Protocol with pre-built, battle-tested contracts. Focus on your innovation, not protocol complexity.**
```bash
npm install @glue-finance/expansions-pack
```
## ๐ฏ What is This?
The Glue Expansions Pack provides **three core tools** for building with Glue Protocol:
### **1. Sticky Assets** - Create Tokens Native to Glue
Build tokens that integrate natively with Glue Protocol. Automatic glue creation, collateral backing, and holder redemption.
```solidity
import "@glue-finance/expansions-pack/base/StickyAsset.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract MyToken is ERC20, StickyAsset {
constructor()
ERC20("My Token", "MTK")
StickyAsset("https://metadata.json", [true, false])
{
_mint(msg.sender, 1000000 * 10**18);
}
}
```
**Use StickyAsset when:** Creating tokens that should have native Glue integration (collateral backing, holder redemption)
### **2. GluedTools** - Build Smart Contracts That Interact with Glue
Build routers, aggregators, or any contract that needs to interact with glued assets. Includes helpers for transfers, burns, math, and more.
```solidity
import "@glue-finance/expansions-pack/base/GluedToolsERC20.sol";
contract MyRouter is GluedToolsERC20 {
function swap(address token, uint256 amount) external {
address glue = _initializeGlue(token);
_transferFromAsset(token, msg.sender, address(this), amount);
// Use helper functions for safe operations
}
}
```
**Use GluedTools when:** Building applications that interact with Glue Protocol
**Use GluedToolsERC20 when:** Only working with ERC20 tokens (smaller bytecode)
### **3. GluedLoanReceiver** - Build Flash Loan Applications
Create flash loan bots, arbitrage strategies, or MEV applications with automatic repayment handling.
```solidity
import "@glue-finance/expansions-pack/base/GluedLoanReceiver.sol";
contract ArbitrageBot is GluedLoanReceiver {
function _executeFlashLoanLogic(bytes memory params) internal override returns (bool) {
address token = getCurrentCollateral();
uint256 borrowed = getCurrentTotalBorrowed();
// Your arbitrage strategy here
return true; // Repayment is automatic!
}
}
```
**Use GluedLoanReceiver when:** Building flash loan applications (arbitrage, MEV, liquidations)
## ๐ฆ Full Package Contents
### **Creating Sticky Assets**
| Contract | Purpose |
|----------|---------|
| `StickyAsset` | Standard sticky asset (constructor-based) |
| `InitStickyAsset` | Proxy-friendly sticky asset (factory pattern) |
### **Building on Glue**
| Contract | Purpose | Size |
|----------|---------|------|
| `GluedToolsBase` | Complete base toolkit (ERC20 + ERC721) | 606 lines |
| `GluedToolsERC20Base` | Complete base toolkit (ERC20 only) | 486 lines |
| `GluedTools` | Full-featured (ERC20 + ERC721 + GluedMath) | 355 lines |
| `GluedToolsERC20` | Full-featured (ERC20 only + GluedMath) | 279 lines |
| `GluedLoanReceiver` | Flash loan receiver | 627 lines |
### **Libraries**
| Library | Purpose |
|---------|---------|
| `GluedConstants` | Protocol addresses & constants (single source of truth) |
| `GluedMath` | High-precision math, decimal conversion |
### **Interfaces**
`IGlueERC20`, `IGlueERC721`, `IGlueStickERC20`, `IGlueStickERC721`, `IStickyAsset`, `IInitStickyAsset`, `IGluedHooks`, `IGluedLoanReceiver`
### **Testing Mocks**
`MockUnglueERC20`, `MockUnglueERC721`, `MockBatchUnglueERC20`, `MockBatchUnglueERC721`, `MockFlashLoan`, `MockGluedLoan`, `MockStickyAsset`, `MockGluedLoanReceiver`
### **Examples**
`BasicStickyToken`, `AdvancedStickyToken`, `ExampleArbitrageBot`
## ๐ ๏ธ Helper Functions You Get
### **From GluedToolsBase** (Complete base - all sticky assets and tools inherit these)
```solidity
// Safe transfers (handles tax tokens, ETH, ERC20, ERC721)
_transferAsset(token, to, amount, tokenIds, fungible);
_transferFromAsset(token, from, to, amount, tokenIds, fungible) returns (actualReceived);
// Glue operations
_initializeGlue(asset, fungible) returns (glue);
_hasAGlue(asset, fungible) returns (bool);
// Balances
_balanceOfAsset(token, account, fungible) returns (balance);
_getGlueBalances(asset, collaterals, fungible) returns (balances);
_getTotalSupply(asset, fungible) returns (supply);
// NFT helpers
_getNFTOwner(nftContract, tokenId) returns (owner);
```
### **From GluedTools** (Advanced features + GluedMath)
```solidity
// Burns to glue
_burnAsset(token, amount, fungible, tokenIds);
_burnAssetFrom(token, from, amount, fungible, tokenIds);
// High-precision math (512-bit, prevents overflow)
_md512(a, b, denominator) returns (result);
_md512Up(a, b, denominator) returns (result); // rounds up
// Decimal conversion (USDC โ WETH, any token โ any token)
_adjustDecimals(amount, tokenIn, tokenOut) returns (adjusted);
// Batch operations
_batchTransferAsset(token, recipients, amounts, tokenIds, total, fungible);
// Additional utilities
_getTokenDecimals(token, fungible) returns (decimals);
_handleExcess(token, amount, glue);
_transferAssetChecked(token, to, amount, tokenIds, fungible) returns (actual);
```
**Why use helpers?**
- โ
Handles tax tokens automatically
- โ
Safe for ETH, ERC20, and ERC721
- โ
Prevents overflow with 512-bit math
- โ
Automatic decimal adjustments
- โ
Battle-tested across all contracts
## ๐๏ธ Architecture
```
GluedConstants (86 lines)
โโ Protocol addresses (GLUE_STICK_ERC20, GLUE_STICK_ERC721)
โโ Common constants (PRECISION, ETH_ADDRESS, DEAD_ADDRESS)
โโ Interface imports
โ
GluedToolsBase (606L) / GluedToolsERC20Base (486L)
โโ Safe transfer functions
โโ Glue initialization
โโ Balance helpers
โ
GluedTools (355L) / GluedToolsERC20 (279L)
โโ All Min features
โโ GluedMath integration
โโ Burn functions
โโ Advanced operations
โ
Your Contract
โโ Inherits everything above
```
**Single source of truth. Zero duplication. Clean inheritance.**
## ๐ฏ Quick Guide
### **I want to create a token backed by collateral**
โ Use `StickyAsset` (standard) or `InitStickyAsset` (for factories)
```solidity
contract MyToken is ERC20, StickyAsset {
constructor()
ERC20("My Token", "MTK")
StickyAsset("https://metadata.json", [true, false])
{
_mint(msg.sender, 1000000 * 10**18);
}
}
```
### **I want to build an app that interacts with Glue**
โ Use `GluedTools` (supports ERC20 + ERC721) or `GluedToolsERC20` (ERC20 only, smaller)
```solidity
contract MyRouter is GluedToolsERC20 {
function myFunction() external {
// Access all helpers: _transferAsset, _burnAsset, _md512, etc.
}
}
```
### **I want to build a flash loan bot**
โ Use `GluedLoanReceiver`
```solidity
contract Bot is GluedLoanReceiver {
function _executeFlashLoanLogic(bytes memory) internal override returns (bool) {
// Your strategy - repayment is automatic
return true;
}
}
```
## ๐ก How Glue Works
1. **Apply Glue** - `applyTheGlue(token)` creates a Glue contract for your token
2. **Add Collateral** - Anyone sends ETH, USDC, or any ERC20 to the Glue
3. **Holders Burn to Claim** - Burn tokens โ receive `(burned / totalSupply) ร collateral ร (1 - 0.1% fee)`
4. **Flash Loans Available** - Borrow from glue collateral, repay + 0.01% fee
**Fully onchain. No oracles. Trustless. Permissionless.**
## ๐ Deployed Networks
| Network | Chain ID | Status |
|---------|----------|--------|
| Ethereum Mainnet | 1 | โ
|
| Base | 8453 | โ
|
| Optimism | 10 | โ
|
| Sepolia (testnet) | 11155111 | โ
|
| Base Sepolia | 84532 | โ
|
| Optimism Sepolia | 11155420 | โ
|
**Same addresses on all networks.**
**Want another network?** [Join Discord](https://discord.gg/ZxqcBxC96w)
## ๐ License & Protocol Addresses
**BUSL-1.1 License** - Free to use with official addresses:
- โ
Build and deploy sticky assets
- โ
Create applications on Glue
- โ
Earn money from your integrations
**You CANNOT:**
- โ Modify these addresses in GluedConstants:
- `GLUE_STICK_ERC20`: `0x5fEe29873DE41bb6bCAbC1E4FB0Fc4CB26a7Fd74`
- `GLUE_STICK_ERC721`: `0xe9B08D7dC8e44F1973269E7cE0fe98297668C257`
See [LICENSE](./LICENSE) for complete terms.
## ๐ Documentation
- **[Protocol Wiki](https://wiki.glue.finance)** - Complete Glue Protocol documentation
- **[V2 Update Guide](./doc/V2_UPDATE.md)** - What's new in v2.0 (for existing users)
- **[vibecodersBible.txt](./doc/vibecodersBible.txt)** - AI context guide (paste in Claude/ChatGPT)
- **[Solidity Docs](https://docs.soliditylang.org/en/v0.8.33/)** - Language reference
## ๐จ Examples
### Revenue-Sharing Token (with hooks)
```solidity
contract RevenueToken is ERC20, StickyAsset {
address public treasury;
constructor(address _treasury)
ERC20("Revenue", "REV")
StickyAsset("https://metadata.json", [true, true]) // Enable hooks
{
treasury = _treasury;
_mint(msg.sender, 1000000 * 10**18);
}
// 10% of withdrawn collateral goes to treasury
function _calculateCollateralHookSize(address, uint256 amount) internal pure override returns (uint256) {
return _md512(amount, 1e17, PRECISION); // 10%
}
function _processCollateralHook(address asset, uint256 amount, bool isETH, address) internal override {
if (isETH) {
payable(treasury).transfer(amount);
} else {
_transferAsset(asset, treasury, amount, new uint256[](0), true);
}
}
}
```
### Flash Loan Bot
```solidity
contract MyBot is GluedLoanReceiver {
function executeArbitrage(address stickyAsset, address collateral, uint256 amount) external {
address[] memory glues = new address[](1);
glues[0] = _initializeGlue(stickyAsset);
_requestGluedLoan(true, glues, collateral, amount, "");
}
function _executeFlashLoanLogic(bytes memory) internal override returns (bool) {
// Your strategy
return true;
}
}
```
More examples in `contracts/examples/`
## ๐ Import Paths
```solidity
// Creating sticky assets
import "@glue-finance/expansions-pack/base/StickyAsset.sol";
import "@glue-finance/expansions-pack/base/InitStickyAsset.sol";
// Building apps that interact with Glue (supports ERC20 + ERC721)
import "@glue-finance/expansions-pack/base/GluedTools.sol";
import "@glue-finance/expansions-pack/tools/GluedToolsBase.sol"; // Minimal version
// Building apps (ERC20 only - better if you don't use NFTs)
import "@glue-finance/expansions-pack/base/GluedToolsERC20.sol";
import "@glue-finance/expansions-pack/tools/GluedToolsERC20Base.sol"; // Minimal version
// Flash loans
import "@glue-finance/expansions-pack/base/GluedLoanReceiver.sol";
// Libraries
import "@glue-finance/expansions-pack/libraries/GluedMath.sol";
import "@glue-finance/expansions-pack/libraries/GluedConstants.sol";
// Interfaces
import "@glue-finance/expansions-pack/interfaces/IGlueERC20.sol";
import "@glue-finance/expansions-pack/interfaces/IGlueERC721.sol";
```
## ๐ก Key Concepts
### **Sticky Asset**
A token (ERC20 or ERC721) that has been "glued" - it has a Glue contract holding collateral. Token holders can burn tokens to receive proportional collateral.
### **Glue**
A contract that holds collateral for a specific sticky asset. Created by calling `applyTheGlue(token)`.
### **Ungluing**
Burning sticky tokens to withdraw collateral: `(tokens burned / total supply) ร collateral ร (1 - 0.1% fee)`
### **Glued Loan**
Flash loan from glue collateral. Borrow, execute strategy, auto-repay + 0.01% fee.
### **Hooks**
Custom logic executed during ungluing. Use to capture fees, redistribute value, or implement custom mechanics.
## ๐ Best Practices
### **DO:**
- โ
Use `_transferAsset()` for transfers (handles tax tokens automatically)
- โ
Use `_burnAsset()` for burns (safe, automatic)
- โ
Use `_md512()` for fee calculations (high-precision, prevents overflow)
- โ
Use `address(0)` for ETH
- โ
Use `PRECISION` (1e18) for percentages
- โ
Add limits to loops (`require(arr.length <= 100)`)
- โ
Inherit from appropriate base contract
### **DON'T:**
- โ Modify GLUE_STICK addresses (license violation)
- โ Use `IERC20.transfer()` (doesn't handle tax tokens)
- โ Use `payable.transfer()` (can fail silently)
- โ Use raw `* /` for fees (overflow risk)
- โ Manually handle decimals (use `_adjustDecimals()`)
- โ Create unbounded loops
## ๐ง Helper Functions Reference
### **Transfers**
```solidity
_transferAsset(token, to, amount, tokenIds, fungible);
_transferFromAsset(token, from, to, amount, tokenIds, fungible) returns (actualReceived);
```
### **Burns**
```solidity
_burnAsset(token, amount, fungible, tokenIds);
_burnAssetFrom(token, from, amount, fungible, tokenIds);
```
### **Math**
```solidity
_md512(a, b, denominator); // High-precision mul-div
_md512Up(a, b, denominator); // Rounds up
_adjustDecimals(amount, tokenIn, tokenOut); // Decimal conversion
```
### **Balances**
```solidity
_balanceOfAsset(token, account, fungible);
_getGlueBalances(asset, collaterals, fungible);
```
### **Glue Operations**
```solidity
_initializeGlue(asset, fungible) returns (glue);
_hasAGlue(asset, fungible) returns (bool);
```
**Full reference:** See contract files or [V2_UPDATE.md](./doc/V2_UPDATE.md)
## ๐ Why Glue Protocol?
- **Fully Onchain** - No oracles, no keepers, no offchain dependencies
- **Composable** - Works with ANY ERC20/ERC721, integrates with ANY DeFi protocol
- **Capital Efficient** - Flash loans across multiple sources, batch operations
- **Developer Friendly** - 3-line integration, inherit-and-done
- **Battle-Tested** - Live on mainnet handling real value
## ๐ Package Structure
```
contracts/
โโโ base/
โ โโโ StickyAsset.sol (Create sticky assets)
โ โโโ InitStickyAsset.sol (Proxy-friendly version)
โ โโโ GluedLoanReceiver.sol (Flash loans)
โ โโโ GluedTools.sol (Full helpers, ERC20 + ERC721)
โ โโโ GluedToolsERC20.sol (Full helpers, ERC20 only)
โโโ tools/
โ โโโ GluedToolsBase.sol (Complete base toolkit, ERC20 + ERC721)
โ โโโ GluedToolsERC20Base.sol (Complete base toolkit, ERC20 only)
โโโ libraries/
โ โโโ GluedConstants.sol (Protocol constants)
โ โโโ GluedMath.sol (High-precision math)
โโโ interfaces/
โ โโโ [All protocol interfaces]
โโโ mocks/
โ โโโ [Testing mocks]
โโโ examples/
โโโ [Ready-to-deploy examples]
```
## ๐ค AI-Assisted Development
**Using Claude, ChatGPT, or other AI?**
Paste [`doc/vibecodersBible.txt`](./doc/vibecodersBible.txt) into your chat for:
- โ
Expert Glue Protocol assistance
- โ
Always uses helper functions (never raw operations)
- โ
Creates TypeScript tests + deployment scripts automatically
- โ
Suggests fully onchain solutions
- โ
Protects protocol addresses (won't help modify them)
- โ
Explains onchain vs offchain tradeoffs
- โ
Suggests revenue generation ideas
## ๐งช Testing
Use included mocks for easy testing:
```solidity
import "@glue-finance/expansions-pack/mocks/MockUnglueERC20.sol";
MockUnglueERC20 mockGlue = new MockUnglueERC20();
mockGlue.setStickyAsset(myToken);
mockGlue.addCollateral(USDC, 1000e6);
mockGlue.unglue([USDC], 100e18, recipient);
```
Mocks simulate real protocol behavior without full deployment.
## ๐ Resources
- ๐ **[Wiki](https://wiki.glue.finance)** - Complete documentation
- ๐ฌ **[Discord](https://discord.gg/ZxqcBxC96w)** - Community & support
- ๐ป **[GitHub](https://github.com/glue-finance/glue-ExpansionsPack)** - Source code
- ๐ **[Website](https://glue.finance)** - Learn more
- ๐ฆ **[Twitter/X](https://x.com/glue_finance)** - Updates
## ๐ Coming from v1.x?
See [V2_UPDATE.md](./doc/V2_UPDATE.md) for:
- What's new in v2.0
- Why the architecture is superior
- Migration guide
- Performance improvements (27% smaller bytecode!)
- Development speed improvements (10-96x faster!)
**No code changes needed for existing StickyAsset users.**
## ๐ What You Get
- **31 Contracts** ready to use
- **6 Networks** supported (+ more on request)
- **Helper Functions** for safe operations
- **Testing Mocks** for easy testing
- **Professional Documentation** throughout
## ๐งฌ Blueprints - Glue-Empowered Token Standards
Blueprints are **next-generation token standards** that leverage Glue Protocol to solve fundamental problems in existing ERCs. These are ready-to-inherit contracts that give your tokens superpowers.
### **ERC721G** - NFTs with Guaranteed Royalty Enforcement
The first blueprint tackles the creator royalty problem. Unlike ERC-2981 (merely informational) or ERC721C (requires permissioned marketplace whitelisting), **ERC721G enforces royalties at the protocol level while remaining fully permissionless and backward compatible with ANY marketplace**.
**Key Features:**
- ๐ **Enforced Royalties** - Royalty payment is a prerequisite for transferability
- ๐ **Permissionless** - Works with ANY marketplace, no whitelisting required
- โก **Deferred Payments** - Compatible with marketplace flows (pay after transfer)
- ๐ฐ **Dynamic Floor Price** - Derived from GLUE Protocol collateral oracle
- ๐ **transferFrom2** - New transfer primitive with native royalty enforcement
- โ
**Backward Compatible** - All standard ERC721 functions work normally
๐ **[More โ](https://github.com/lalilulel0x/ERC721G)**
**Built with โค๏ธ by La-Li-Lu-Le-Lo (@lalilulel0z) and the Glue Finance Team**
๐ **Start building:** `npm install @glue-finance/expansions-pack`