Comparing arbitrum with maker
arbitrum
View full →Author
@0xinit
Stars
53
Repository
0xinit/cryptoskills
Arbitrum
Arbitrum is the largest Ethereum L2 by TVL, running an optimistic rollup via the Nitro execution engine. Nitro compiles a modified Geth (go-ethereum) to WASM, enabling full EVM equivalence with fraud proofs. Arbitrum One targets general-purpose DeFi, Arbitrum Nova uses AnyTrust (data availability committee) for high-throughput gaming/social, and Orbit lets teams launch custom L3s settling to Arbitrum.
What You Probably Got Wrong
AI models trained before late 2024 carry stale assumptions about Arbitrum. These corrections are critical.
block.numberreturns the L1 block number, not L2 — On Arbitrum,block.numberin Solidity returns the L1 Ethereum block number at the time the sequencer processed the transaction. UseArbSys(0x64).arbBlockNumber()for the actual L2 block number.block.timestampis the L1 timestamp — Same issue.block.timestampreflects L1 time. For L2ley timing useArbSys(0x64).arbBlockNumber()and correlate.- Arbitrum does NOT have the same gas model as Ethereum — Every Arbitrum transaction pays two gas components: (1) L2 execution gas (similar to Ethereum but cheaper), and (2) L1 data posting cost (calldata compressed and posted to Ethereum). The L1 component often dominates for data-heavy transactions. Use
NodeInterface.gasEstimateComponents()to get the breakdown. - You need
--legacyfor Foundry deployments — Arbitrum's sequencer does not support EIP-1559 type-2 transactions natively in forge scripts. Use--legacyflag or your deployment will fail with a cryptic RPC error. msg.senderin cross-chain calls is aliased — When an L1 contract sends a message to L2 via retryable tickets,msg.senderon L2 is NOT the L1 contract address. It is the L1 address +0x1111000000000000000000000000000000001111(the "address alias"). This prevents L1/L2 address collision attacks.- Retryable tickets can fail silently — An L1-to-L2 retryable ticket that runs out of gas on L2 does NOT revert on L1. It sits in the retry buffer for 7 days. You must monitor and manually redeem failed retryables, or your cross-chain message is lost after the TTL.
- Withdrawals take 7 days, not minutes — L2-to-L1 messages go through the optimistic rollup challenge period. After calling
ArbSys.sendTxToL1(), the user must wait ~7 days, then execute the message on L1 via the Outbox contract. There is no fast path in the native bridge. - There is no mempool — Arbitrum uses a centralized sequencer that orders transactions on a first-come-first-served basis. There is no traditional mempool, so MEV extraction works differently (no frontrunning via gas price bidding).
Quick Start
Chain Configuration
import { defineChain } from "viem";
import { arbitrum, arbitrumNova, arbitrumSepolia } from "viem/chains";
// Arbitrum One — mainnet
// Chain ID: 42161
// RPC: https://arb1.arbitrum.io/rpc (public, rate-limited)
// Arbitrum Nova — AnyTrust chain for gaming/social
// Chain ID: 42170
// RPC: https://nova.arbitrum.io/rpc
// Arbitrum Sepolia — testnet
// Chain ID: 421614
// RPC: https://sepolia-rollup.arbitrum.io/rpc
Client Setup
import { createPublicClient, createWalletClient, http } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { arbitrum } from "viem/chains";
const publicClient = createPublicClient({
chain: arbitrum,
transport: http(process.env.ARBITRUM_RPC_URL),
});
const account = privateKeyToAccount(
process.env.PRIVATE_KEY as `0x${string}`
);
const walletClient = createWalletClient({
account,
chain: arbitrum,
transport: http(process.env.ARBITRUM_RPC_URL),
});
Chain Details
| Property | Arbitrum One | Arbitrum Nova | Arbitrum Sepolia |
|---|---|---|---|
| Chain ID | 42161 | 42170 | 421614 |
| RPC | https://arb1.arbitrum.io/rpc | https://nova.arbitrum.io/rpc | https://sepolia-rollup.arbitrum.io/rpc |
| Explorer | https://arbiscan.io | https://nova.arbiscan.io | https://sepolia.arbiscan.io |
| Bridge | https://bridge.arbitrum.io | https://bridge.arbitrum.io | https://bridge.arbitrum.io |
| Native Token | ETH | ETH | ETH |
| Block Time | ~0.25s | ~0.25s | ~0.25s |
| Finality | ~7 days (challenge period) | ~7 days | ~7 days |
Deployment
Foundry Deployment
The --legacy flag is required — Arbitrum's sequencer does not natively support EIP-1559 type-2 transaction envelopes in forge broadcast.
# Deploy to Arbitrum One
forge create src/MyContract.sol:MyContract \
--rpc-url $ARBITRUM_RPC_URL \
--private-key $PRIVATE_KEY \
--legacy
# Deploy to Arbitrum Sepolia (testnet)
forge create src/MyContract.sol:MyContract \
--rpc-url https://sepolia-rollup.arbitrum.io/rpc \
--private-key $PRIVATE_KEY \
--legacy
# Using forge script
forge script script/Deploy.s.sol:DeployScript \
--rpc-url $ARBITRUM_RPC_URL \
--private-key $PRIVATE_KEY \
--broadcast \
--legacy
Hardhat Deployment
// hardhat.config.ts
import { HardhatUserConfig } from "hardhat/config";
const config: HardhatUserConfig = {
solidity: "0.8.24",
networks: {
arbitrumOne: {
url: process.env.ARBITRUM_RPC_URL ?? "https://arb1.arbitrum.io/rpc",
accounts: [process.env.PRIVATE_KEY!],
chainId: 42161,
},
arbitrumSepolia: {
url: "https://sepolia-rollup.arbitrum.io/rpc",
accounts: [process.env.PRIVATE_KEY!],
chainId: 421614,
},
},
etherscan: {
apiKey: {
arbitrumOne: process.env.ARBISCAN_API_KEY!,
arbitrumSepolia: process.env.ARBISCAN_API_KEY!,
},
},
};
export default config;
Contract Verification
# Verify on Arbiscan (Foundry)
forge verify-contract \
--chain-id 42161 \
--etherscan-api-key $ARBISCAN_API_KEY \
--compiler-version v0.8.24 \
$CONTRACT_ADDRESS \
src/MyContract.sol:MyContract
# Verify with constructor args
forge verify-contract \
--chain-id 42161 \
--etherscan-api-key $ARBISCAN_API_KEY \
--constructor-args $(cast abi-encode "constructor(address,uint256)" 0xYourAddress 1000) \
$CONTRACT_ADDRESS \
src/MyContract.sol:MyContract
# Verify on Sourcify
forge verify-contract \
--chain-id 42161 \
--verifier sourcify \
$CONTRACT_ADDRESS \
src/MyContract.sol:MyContract
Cross-Chain Messaging
L1 to L2: Retryable Tickets
Retryable tickets are Arbitrum's mechanism for sending messages from Ethereum L1 to Arbitrum L2. The L1 Inbox contract accepts the message and ETH for L2 gas, then the sequencer auto-executes it on L2.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
interface IInbox {
/// @notice Create a retryable ticket to send an L1→L2 message
/// @param to L2 destination address
/// @param l2CallValue ETH value to send to L2 destination
/// @param maxSubmissionCost Max cost for L2 submission (refund if overestimated)
/// @param excessFeeRefundAddress L2 address to refund excess fees
/// @param callValueRefundAddress L2 address to refund call value on failure
/// @param gasLimit L2 gas limit for execution
/// @param maxFeePerGas Max L2 gas price
/// @param data L2 calldata
function createRetryableTicket(
address to,
uint256 l2CallValue,
uint256 maxSubmissionCost,
address excessFeeRefundAddress,
address callValueRefundAddress,
uint256 gasLimit,
uint256 maxFeePerGas,
bytes calldata data
) external payable returns (uint256);
}
// TypeScript: send L1→L2 message via retryable ticket
import { createPublicClient, createWalletClient, http, parseEther } from "viem";
import { mainnet } from "viem/chains";
const INBOX = "0x4Dbd4fc535Ac27206064B68FfCf827b0A60BAB3f" as const;
const inboxAbi = [
{
name: "createRetryableTicket",
type: "function",
stateMutability: "payable",
inputs: [
{ name: "to", type: "address" },
{ name: "l2CallValue", type: "uint256" },
{ name: "maxSubmissionCost", type: "uint256" },
{ name: "excessFeeRefundAddress", type: "address" },
{ name: "callValueRefundAddress", type: "address" },
{ name: "gasLimit", type: "uint256" },
{ name: "maxFeePerGas", type: "uint256" },
{ name: "data", type: "bytes" },
],
outputs: [{ name: "", type: "uint256" }],
},
] as const;
const l1PublicClient = createPublicClient({
chain: mainnet,
transport: http(process.env.ETHEREUM_RPC_URL),
});
const maxSubmissionCost = parseEther("0.001");
const gasLimit = 1_000_000n;
const maxFeePerGas = 100_000_000n; // 0.1 gwei
// Total ETH needed: l2CallValue + maxSubmissionCost + (gasLimit * maxFeePerGas)
const totalValue = 0n + maxSubmissionCost + gasLimit * maxFeePerGas;
const { request } = await l1PublicClient.simulateContract({
address: INBOX,
abi: inboxAbi,
functionName: "createRetryableTicket",
args: [
"0xYourL2ContractAddress", // to
0n, // l2CallValue
maxSubmissionCost, // maxSubmissionCost
account.address, // excessFeeRefundAddress
account.address, // callValueRefundAddress
gasLimit, // gasLimit
maxFeePerGas, // maxFeePerGas
"0x", // data (encoded L2 function call)
],
value: totalValue,
account: account.address,
});
const hash = await walletClient.writeContract(request);
L2 to L1: ArbSys.sendTxToL1
L2-to-L1 messages go through the 7-day challenge period before they can be executed on L1.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
interface IArbSys {
/// @notice Send a transaction from L2 to L1
/// @param destination L1 destination address
/// @param data L1 calldata
/// @return unique message ID
function sendTxToL1(
address destination,
bytes calldata data
) external payable returns (uint256);
/// @notice Get the current L2 block number
function arbBlockNumber() external view returns (uint256);
}
// ArbSys is at a fixed precompile address on all Arbitrum chains
IArbSys constant ARBSYS = IArbSys(0x0000000000000000000000000000000000000064);
contract L2ToL1Sender {
event L2ToL1MessageSent(uint256 indexed messageId, address destination);
function sendMessageToL1(
address l1Target,
bytes calldata l1Calldata
) external payable {
uint256 messageId = ARBSYS.sendTxToL1{value: msg.value}(
l1Target,
l1Calldata
);
emit L2ToL1MessageSent(messageId, l1Target);
}
}
Address Aliasing
When an L1 contract sends a retryable ticket, the msg.sender seen on L2 is the aliased address:
L2 alias = L1 address + 0x1111000000000000000000000000000000001111
// Reverse the alias to get the original L1 sender
function undoL1ToL2Alias(address l2Address) internal pure returns (address) {
uint160 offset = uint160(0x1111000000000000000000000000000000001111);
unchecked {
return address(uint160(l2Address) - offset);
}
}
// Verify an L2 call came from a specific L1 contract
modifier onlyFromL1Contract(address expectedL1Sender) {
require(
undoL1ToL2Alias(msg.sender) == expectedL1Sender,
"NOT_FROM_L1_CONTRACT"
);
_;
}
ArbOS Precompiles
Arbitrum provides system-level functionality through precompile contracts at fixed addresses. These are available on all Arbitrum chains.
ArbSys (0x0000000000000000000000000000000000000064)
Core system functions for L2 operations.
interface IArbSys {
function arbBlockNumber() external view returns (uint256);
function arbBlockHash(uint256 blockNumber) external view returns (bytes32);
function arbChainID() external view returns (uint256);
function arbOSVersion() external view returns (uint256);
function sendTxToL1(address dest, bytes calldata data) external payable returns (uint256);
function withdrawEth(address dest) external payable returns (uint256);
}
const arbSysAbi = [
{
name: "arbBlockNumber",
type: "function",
stateMutability: "view",
inputs: [],
outputs: [{ name: "", type: "uint256" }],
},
{
name: "withdrawEth",
type: "function",
stateMutability: "payable",
inputs: [{ name: "destination", type: "address" }],
outputs: [{ name: "", type: "uint256" }],
},
] as const;
const ARBSYS = "0x0000000000000000000000000000000000000064" as const;
const l2BlockNumber = await publicClient.readContract({
address: ARBSYS,
abi: arbSysAbi,
functionName: "arbBlockNumber",
});
ArbRetryableTx (0x000000000000000000000000000000000000006E)
Manage retryable tickets on L2.
interface IArbRetryableTx {
/// @notice Redeem a retryable ticket that failed auto-execution
function redeem(bytes32 ticketId) external;
/// @notice Get the TTL for retryable tickets (default: 7 days)
function getLifetime() external view returns (uint256);
/// @notice Get the timeout timestamp for a specific ticket
function getTimeout(bytes32 ticketId) external view returns (uint256);
/// @notice Extend the lifetime of a retryable ticket
function keepalive(bytes32 ticketId) external returns (uint256);
}
ArbGasInfo (0x000000000000000000000000000000000000006C)
Gas pricing information, especially the L1 data cost component.
interface IArbGasInfo {
/// @notice Get gas prices: [perL2Tx, perL1CalldataUnit, perStorageAlloc, perArbGasBase, perArbGasCongestion, perArbGasTotal]
function getPricesInWei() external view returns (uint256, uint256, uint256, uint256, uint256, uint256);
/// @notice Get estimated L1 base fee
function getL1BaseFeeEstimate() external view returns (uint256);
/// @notice Get L1 gas pricing parameters
function getL1GasPriceEstimate() external view returns (uint256);
}
const arbGasInfoAbi = [
{
name: "getPricesInWei",
type: "function",
stateMutability: "view",
inputs: [],
outputs: [
{ name: "perL2Tx", type: "uint256" },
{ name: "perL1CalldataUnit", type: "uint256" },
{ name: "perStorageAlloc", type: "uint256" },
{ name: "perArbGasBase", type: "uint256" },
{ name: "perArbGasCongestion", type: "uint256" },
{ name: "perArbGasTotal", type: "uint256" },
],
},
{
name: "getL1BaseFeeEstimate",
type: "function",
stateMutability: "view",
inputs: [],
outputs: [{ name: "", type: "uint256" }],
},
] as const;
const ARBGASINFO = "0x000000000000000000000000000000000000006C" as const;
const prices = await publicClient.readContract({
address: ARBGASINFO,
abi: arbGasInfoAbi,
functionName: "getPricesInWei",
});
const l1BaseFee = await publicClient.readContract({
address: ARBGASINFO,
abi: arbGasInfoAbi,
functionName: "getL1BaseFeeEstimate",
});
NodeInterface (0x00000000000000000000000000000000000000C8)
Virtual contract for gas estimation — not callable from other contracts, only via eth_call / eth_estimateGas.
interface INodeInterface {
/// @notice Estimate gas for a retryable ticket submission
function estimateRetryableTicket(
address sender,
uint256 deposit,
address to,
uint256 l2CallValue,
address excessFeeRefundAddress,
address callValueRefundAddress,
bytes calldata data
) external;
/// @notice Get gas cost breakdown: gasEstimate, gasEstimateForL1, baseFee, l1BaseFeeEstimate
function gasEstimateComponents(
address to,
bool contractCreation,
bytes calldata data
) external payable returns (uint64, uint64, uint256, uint256);
}
const nodeInterfaceAbi = [
{
name: "gasEstimateComponents",
type: "function",
stateMutability: "payable",
inputs: [
{ name: "to", type: "address" },
{ name: "contractCreation", type: "bool" },
{ name: "data", type: "bytes" },
],
outputs: [
{ name: "gasEstimate", type: "uint64" },
{ name: "gasEstimateForL1", type: "uint64" },
{ name: "baseFee", type: "uint256" },
{ name: "l1BaseFeeEstimate", type: "uint256" },
],
},
] as const;
const NODE_INTERFACE = "0x00000000000000000000000000000000000000C8" as const;
// Estimate gas with L1/L2 breakdown
const result = await publicClient.simulateContract({
address: NODE_INTERFACE,
abi: nodeInterfaceAbi,
functionName: "gasEstimateComponents",
args: [
"0xTargetContract",
false,
"0xEncodedCalldata",
],
});
const [totalGas, l1Gas, baseFee, l1BaseFee] = result.result;
// L2 gas = totalGas - l1Gas
Gas Model
Arbitrum's gas model has two components. Understanding this is critical for accurate cost estimation.
Two-Component Gas
| Component | Source | Scales With |
|---|---|---|
| L2 execution gas | ArbOS computation | Opcodes executed (similar to Ethereum) |
| L1 data posting cost | Calldata posted to Ethereum | Transaction size in bytes |
The L1 data cost is computed as:
L1 cost = L1 base fee * (calldata bytes * 16 + overhead)
This L1 cost is converted to L2 gas units and added to the total gas used. For data-heavy transactions (large calldata, many storage writes that get batched), the L1 component can be 80%+ of total cost.
Gas Estimation
import { encodeFunctionData, formatEther } from "viem";
async function estimateArbitrumGas(
publicClient: PublicClient,
to: `0x${string}`,
data: `0x${string}`
) {
const nodeInterfaceAbi = [
{
name: "gasEstimateComponents",
type: "function",
stateMutability: "payable",
inputs: [
{ name: "to", type: "address" },
{ name: "contractCreation", type: "bool" },
{ name: "data", type: "bytes" },
],
outputs: [
{ name: "gasEstimate", type: "uint64" },
{ name: "gasEstimateForL1", type: "uint64" },
{ name: "baseFee", type: "uint256" },
{ name: "l1BaseFeeEstimate", type: "uint256" },
],
},
] as const;
const { result } = await publicClient.simulateContract({
address: "0x00000000000000000000000000000000000000C8",
abi: nodeInterfaceAbi,
functionName: "gasEstimateComponents",
args: [to, false, data],
});
const [totalGas, l1Gas, baseFee, l1BaseFee] = result;
const l2Gas = totalGas - l1Gas;
return {
totalGas,
l1Gas,
l2Gas,
baseFee,
l1BaseFee,
estimatedCostWei: BigInt(totalGas) * baseFee,
estimatedCostEth: formatEther(BigInt(totalGas) * baseFee),
};
}
Token Bridge
Bridging ETH (L1 to L2)
const INBOX = "0x4Dbd4fc535Ac27206064B68FfCf827b0A60BAB3f" as const;
const inboxAbi = [
{
name: "depositEth",
type: "function",
stateMutability: "payable",
inputs: [],
outputs: [{ name: "", type: "uint256" }],
},
] as const;
// Deposit 0.1 ETH from L1 to L2 (arrives at same address on L2)
const { request } = await l1PublicClient.simulateContract({
address: INBOX,
abi: inboxAbi,
functionName: "depositEth",
value: parseEther("0.1"),
account: account.address,
});
const hash = await l1WalletClient.writeContract(request);
const receipt = await l1PublicClient.waitForTransactionReceipt({ hash });
if (receipt.status !== "success") throw new Error("ETH deposit failed");
// ETH appears on L2 within ~10 minutes
Bridging ETH (L2 to L1)
// Withdraw ETH from L2 to L1 via ArbSys precompile
const ARBSYS = "0x0000000000000000000000000000000000000064" as const;
const arbSysAbi = [
{
name: "withdrawEth",
type: "function",
stateMutability: "payable",
inputs: [{ name: "destination", type: "address" }],
outputs: [{ name: "", type: "uint256" }],
},
] as const;
const { request } = await l2PublicClient.simulateContract({
address: ARBSYS,
abi: arbSysAbi,
functionName: "withdrawEth",
args: [account.address], // L1 destination
value: parseEther("0.1"),
account: account.address,
});
const hash = await l2WalletClient.writeContract(request);
// After 7-day challenge period, claim on L1 via Outbox contract
Bridging ERC20 Tokens (L1 to L2)
ERC20 tokens bridge through the Gateway Router, which routes to the appropriate gateway (standard, custom, or WETH).
const GATEWAY_ROUTER = "0x72Ce9c846789fdB6fC1f34aC4AD25Dd9ef7031ef" as const;
const gatewayRouterAbi = [
{
name: "outboundTransfer",
type: "function",
stateMutability: "payable",
inputs: [
{ name: "_token", type: "address" },
{ name: "_to", type: "address" },
{ name: "_amount", type: "uint256" },
{ name: "_maxGas", type: "uint256" },
{ name: "_gasPriceBid", type: "uint256" },
{ name: "_data", type: "bytes" },
],
outputs: [{ name: "", type: "bytes" }],
},
{
name: "getGateway",
type: "function",
stateMutability: "view",
inputs: [{ name: "_token", type: "address" }],
outputs: [{ name: "", type: "address" }],
},
] as const;
const USDC_L1 = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48" as const;
// Step 1: Approve the gateway (not the router) to spend tokens
const gateway = await l1PublicClient.readContract({
address: GATEWAY_ROUTER,
abi: gatewayRouterAbi,
functionName: "getGateway",
args: [USDC_L1],
});
// Step 2: approve gateway, then call outboundTransfer on the router
// The _data param encodes maxSubmissionCost and extra data
import { encodeAbiParameters, parseAbiParameters } from "viem";
const maxSubmissionCost = parseEther("0.001");
const extraData = encodeAbiParameters(
parseAbiParameters("uint256, bytes"),
[maxSubmissionCost, "0x"]
);
const bridgeAmount = 1000_000000n; // 1000 USDC (6 decimals)
const gasLimit = 300_000n;
const gasPriceBid = 100_000_000n; // 0.1 gwei
const totalValue = maxSubmissionCost + gasLimit * gasPriceBid;
const { request } = await l1PublicClient.simulateContract({
address: GATEWAY_ROUTER,
abi: gatewayRouterAbi,
functionName: "outboundTransfer",
args: [
USDC_L1,
account.address,
bridgeAmount,
gasLimit,
gasPriceBid,
extraData,
],
value: totalValue,
account: account.address,
});
Gateway Types
| Gateway | Address (L1) | Purpose |
|---|---|---|
| Standard ERC20 | 0xa3A7B6F88361F48403514059F1F16C8E78d60EeC | Default for most ERC20 tokens |
| Custom | Varies per token | Tokens needing custom L1/L2 logic |
| WETH | 0xd92023E9d9911199a6711321D1277285e6d4e2db | Handles WETH unwrap/wrap across bridge |
Orbit Chains
Orbit allows teams to launch custom L3 chains that settle to Arbitrum One or Nova. These are independent chains with configurable parameters.
Orbit Architecture
Ethereum L1 (settlement)
└── Arbitrum One L2 (execution + DA)
└── Your Orbit L3 (custom chain)
Orbit SDK Setup
import { createRollupPrepareConfig, createRollupPrepareTransactionRequest } from "@arbitrum/orbit-sdk";
// Prepare Orbit chain configuration
const config = createRollupPrepareConfig({
chainId: BigInt(YOUR_CHAIN_ID),
owner: "0xYourOwnerAddress",
chainConfig: {
// Custom gas token, data availability, etc.
homesteadBlock: 0,
daoForkBlock: null,
daoForkSupport: true,
eip150Block: 0,
eip150Hash: "0x0000000000000000000000000000000000000000000000000000000000000000",
eip155Block: 0,
eip158Block: 0,
byzantiumBlock: 0,
constantinopleBlock: 0,
petersburgBlock: 0,
istanbulBlock: 0,
muirGlacierBlock: 0,
berlinBlock: 0,
londonBlock: 0,
clique: { period: 0, epoch: 0 },
arbitrum: {
EnableArbOS: true,
AllowDebugPrecompiles: false,
DataAvailabilityCommittee: false, // true for AnyTrust
InitialArbOSVersion: 20,
InitialChainOwner: "0xYourOwnerAddress",
GenesisBlockNum: 0,
},
},
});
When to Use Orbit
| Use Case | Recommendation |
|---|---|
| App-specific chain with custom gas token | Orbit L3 |
| High-throughput gaming with cheap DA | Orbit L3 + AnyTrust |
| General DeFi app | Deploy to Arbitrum One directly |
| Cross-chain interop needed | Deploy to Arbitrum One (better liquidity) |
Key Differences from Ethereum
| Behavior | Ethereum | Arbitrum |
|---|---|---|
block.number | Current L1 block | L1 block number (NOT L2) |
block.timestamp | L1 timestamp | L1 timestamp |
| L2 block number | N/A | ArbSys(0x64).arbBlockNumber() |
| Gas model | Single gas price | L2 gas + L1 data posting cost |
| Transaction type | EIP-1559 (type 2) | Legacy (type 0) recommended |
| Mempool | Public, competitive | No mempool (FCFS sequencer) |
| Finality | ~12 seconds (1 epoch) | ~0.25s soft, ~7 days hard |
msg.sender cross-chain | Same address | Aliased (+0x1111...1111 offset) |
SELFDESTRUCT | Deprecated (EIP-6780) | Same as Ethereum post-Dencun |
| Contract size limit | 24KB (EIP-170) | 24KB (same) |
PUSH0 opcode | Supported (Shanghai) | Supported (Nitro supports it) |
Contract Addresses
Last verified: February 2026
Core Contracts (Arbitrum One)
| Contract | Address |
|---|---|
| Rollup | 0x5eF0D09d1E6204141B4d37530808eD19f60FBa35 |
| Inbox | 0x4Dbd4fc535Ac27206064B68FfCf827b0A60BAB3f |
| Outbox | 0x0B9857ae2D4A3DBe74ffE1d7DF045bb7F96E4840 |
| Bridge | 0x8315177aB297bA92A06054cE80a67Ed4DBd7ed3a |
| SequencerInbox | 0x1c479675ad559DC151F6Ec7ed3FbF8ceE79582B6 |
| Gateway Router (L1) | 0x72Ce9c846789fdB6fC1f34aC4AD25Dd9ef7031ef |
| Standard Gateway (L1) | 0xa3A7B6F88361F48403514059F1F16C8E78d60EeC |
| WETH Gateway (L1) | 0xd92023E9d9911199a6711321D1277285e6d4e2db |
| Gateway Router (L2) | 0x5288c571Fd7aD117beA99bF60FE0846C4E84F933 |
| Standard Gateway (L2) | 0x09e9222E96E7B4AE2a407B98d48e330053351EEe |
ArbOS Precompiles
| Precompile | Address |
|---|---|
| ArbSys | 0x0000000000000000000000000000000000000064 |
| ArbInfo | 0x0000000000000000000000000000000000000065 |
| ArbAddressTable | 0x0000000000000000000000000000000000000066 |
| ArbBLS (deprecated) | 0x0000000000000000000000000000000000000067 |
| ArbFunctionTable (deprecated) | 0x0000000000000000000000000000000000000068 |
| ArbosTest | 0x0000000000000000000000000000000000000069 |
| ArbOwner | 0x0000000000000000000000000000000000000070 |
| ArbGasInfo | 0x000000000000000000000000000000000000006C |
| ArbAggregator | 0x000000000000000000000000000000000000006D |
| ArbRetryableTx | 0x000000000000000000000000000000000000006E |
| ArbStatistics | 0x000000000000000000000000000000000000006F |
| NodeInterface | 0x00000000000000000000000000000000000000C8 |
Token Addresses (Arbitrum One)
| Token | Address |
|---|---|
| ARB | 0x912CE59144191C1204E64559FE8253a0e49E6548 |
| WETH | 0x82aF49447D8a07e3bd95BD0d56f35241523fBab1 |
| USDC (native) | 0xaf88d065e77c8cC2239327C5EDb3A432268e5831 |
| USDC.e (bridged) | 0xFF970A61A04b1cA14834A43f5dE4533eBDDB5CC8 |
| USDT | 0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9 |
| DAI | 0xDA10009cBd5D07dd0CeCc66161FC93D7c9000da1 |
| WBTC | 0x2f2a2543B76A4166549F7aaB2e75Bef0aefC5B0f |
| GMX | 0xfc5A1A6EB076a2C7aD06eD22C90d7E710E35ad0a |
Error Handling
| Error | Cause | Fix |
|---|---|---|
NOT_ENOUGH_FUNDS | Insufficient ETH for L2 gas + L1 data cost | Account for both gas components in estimation |
RETRYABLE_TICKET_CREATION_FAILED | Retryable ticket underfunded | Increase maxSubmissionCost or gasLimit * maxFeePerGas |
ONLY_ROLLUP_OR_OWNER | Calling admin precompile without permission | These are restricted to chain owner |
NO_TICKET_WITH_ID | Redeeming non-existent or expired retryable | Check ticket still exists with getTimeout() |
ALREADY_REDEEMED | Retryable ticket already executed | No action needed — message was delivered |
L1_MSG_NOT_CONFIRMED | Trying to execute L2→L1 message too early | Wait for the 7-day challenge period to elapse |
| Nonce too high/low | Sequencer nonce mismatch | Reset nonce or wait for pending transactions |
Security
Cross-Chain Message Validation
// Always verify the sender of cross-chain messages
// L1→L2: check aliased sender
modifier onlyL1Contract(address expectedL1Sender) {
uint160 offset = uint160(0x1111000000000000000000000000000000001111);
unchecked {
require(
address(uint160(msg.sender) - offset) == expectedL1Sender,
"ONLY_L1_CONTRACT"
);
}
_;
}
// L2→L1: verify via Outbox on L1
modifier onlyL2Contract(address outbox) {
// The Outbox contract provides l2ToL1Sender() during execution
IOutbox(outbox).l2ToL1Sender();
_;
}
Gas Estimation Safety
- Always use
NodeInterface.gasEstimateComponents()instead of plaineth_estimateGas— the latter may not account for L1 data costs correctly in all cases. - Add a 20-30% buffer to gas estimates for L1 data cost fluctuations.
- For retryable tickets, overestimate
maxSubmissionCost— excess is refunded.
Retryable Ticket Monitoring
- Monitor all retryable tickets for auto-redeem failure.
- Failed retryables expire after 7 days — set up alerts.
- Use the
ArbRetryableTxprecompile to check status and manually redeem.
References
maker
View full →Author
@0xinit
Stars
53
Repository
0xinit/cryptoskills
MakerDAO / Sky Protocol
MakerDAO is the protocol behind DAI, the largest decentralized stablecoin on Ethereum. Users lock collateral in Maker Vaults (formerly CDPs) to mint DAI. The protocol charges a stability fee (interest) on outstanding DAI debt and maintains a target price of $1 through the DAI Savings Rate (DSR) and liquidation mechanisms. In 2024, MakerDAO rebranded to Sky Protocol, introducing USDS (upgraded DAI) and SKY (upgraded MKR). Both old and new tokens coexist -- DAI/MKR are not deprecated.
What You Probably Got Wrong
LLMs consistently hallucinate Maker contract interfaces. The system is complex: all accounting happens in the Vat using internal
rad/wad/rayunits. Users interact through DSProxy + DssProxyActions, NOT directly with the Vat. These corrections are non-negotiable.
-
Maker is mid-rebrand to Sky. DAI is becoming USDS. MKR is becoming SKY. Both coexist on mainnet. The old contracts still work. The new Sky contracts wrap/unwrap between old and new tokens. If someone says "Maker" they might mean either system. Always check which token set they need.
-
You do NOT call the Vat directly. Normal users interact through a DSProxy contract that delegates calls to DssProxyActions. The Vat uses internal accounting units (rad = 10^45) that require precise math. DssProxyActions handles this conversion. If you see raw
Vat.frob()calls, you are writing low-level code that will almost certainly have precision errors. -
DAI has two representations. Internal DAI in the Vat (
vat.dai(address)) is measured inrad(10^45). External DAI (the ERC-20 token) is measured inwad(10^18). The DaiJoin adapter converts between them. Never confuse the two. -
Stability fees accrue continuously. The Jug contract compounds the stability fee rate into an ever-increasing
rateaccumulator per collateral type (ilk). Debt is stored as normalized debt (art) in the Vat. Actual debt =art * rate. You MUST calljug.drip(ilk)to update the rate before calculating accurate debt. -
Liquidation 2.0 uses Dutch auctions, not English auctions. The old Flipper (English auctions) was replaced by the Clipper (Dutch auctions) in Liquidation 2.0. Dutch auctions start at a high price and decrease over time. Bidders call
clipper.take(), notbid(). -
Vault IDs (cdpId) are NOT the same as ilk identifiers. An ilk (e.g.,
ETH-A,WBTC-A) defines the collateral type and its risk parameters. A vault (CDP) is a specific user position within an ilk. The CdpManager maps vault IDs to (ilk, urn address) pairs. -
DSR and USDS Savings Rate (sUSDS) are different contracts. The original DSR uses DsrManager/Pot. The new Sky system uses the sUSDS token (ERC-4626 vault). They are separate yield sources with potentially different rates.
Architecture Overview
User -> DSProxy -> DssProxyActions -> | CdpManager (vault management)
| Vat (core accounting)
| Jug (stability fees)
| DaiJoin (DAI minting)
| GemJoin (collateral locking)
User -> DsrManager -> Pot (DAI Savings Rate)
User -> DaiUsds (upgrade) -> USDS token
User -> MkrSky (upgrade) -> SKY token
User -> sUSDS vault -> USDS Savings Rate (ERC-4626)
Keepers -> Dog (liquidation trigger) -> Clipper (Dutch auction)
Unit System (CRITICAL)
Maker uses three fixed-point number types internally. Getting these wrong causes silent precision loss or reverts.
| Unit | Decimals | Used For | Example |
|---|---|---|---|
wad | 10^18 | Token amounts (DAI, collateral), normalized debt (art) | 1.5 DAI = 1500000000000000000 |
ray | 10^27 | Rate accumulators, per-second rates | 1.0 rate = 1000000000000000000000000000 |
rad | 10^45 | Internal DAI balance in Vat (vat.dai()) | wad * ray = rad |
Arithmetic rules:
wad * wad / WAD = wadwad * ray / RAY = wad(used for debt calculation:art * rate)rad / ray = wad(converting internal DAI to external)rad / wad = ray
const WAD = 10n ** 18n;
const RAY = 10n ** 27n;
const RAD = 10n ** 45n;
function wmul(x: bigint, y: bigint): bigint {
return (x * y + WAD / 2n) / WAD;
}
function rmul(x: bigint, y: bigint): bigint {
return (x * y + RAY / 2n) / RAY;
}
function rdiv(x: bigint, y: bigint): bigint {
return (x * RAY + y / 2n) / y;
}
Core Contracts
Vat -- Core Accounting Engine
The Vat is the central ledger. All collateral positions and DAI balances are recorded here. It never touches external tokens directly.
Key state:
ilks[ilk].Art-- total normalized debt for this collateral type (wad)ilks[ilk].rate-- accumulated stability fee rate (ray)ilks[ilk].spot-- collateral price with safety margin (ray)ilks[ilk].line-- debt ceiling for this ilk (rad)ilks[ilk].dust-- minimum debt per vault (rad)urns[ilk][urn].ink-- locked collateral (wad)urns[ilk][urn].art-- normalized debt (wad)dai[address]-- internal DAI balance (rad)
The core function frob(ilk, urn, dink, dart) modifies a vault's collateral (dink) and debt (dart). Positive values add, negative values remove.
CdpManager -- Vault Registry
Maps sequential vault IDs to (ilk, urn) pairs. Users create vaults through CdpManager.open(ilk, usr) which returns a cdpId. The manager owns the Vat urns and delegates control via CdpManager.cdpCan.
const cdpManagerAbi = [
{
name: "open",
type: "function",
stateMutability: "nonpayable",
inputs: [
{ name: "ilk", type: "bytes32" },
{ name: "usr", type: "address" },
],
outputs: [{ name: "", type: "uint256" }],
},
{
name: "ilks",
type: "function",
stateMutability: "view",
inputs: [{ name: "cdpId", type: "uint256" }],
outputs: [{ name: "", type: "bytes32" }],
},
{
name: "urns",
type: "function",
stateMutability: "view",
inputs: [{ name: "cdpId", type: "uint256" }],
outputs: [{ name: "", type: "address" }],
},
{
name: "owns",
type: "function",
stateMutability: "view",
inputs: [{ name: "cdpId", type: "uint256" }],
outputs: [{ name: "", type: "address" }],
},
{
name: "count",
type: "function",
stateMutability: "view",
inputs: [{ name: "usr", type: "address" }],
outputs: [{ name: "", type: "uint256" }],
},
{
name: "first",
type: "function",
stateMutability: "view",
inputs: [{ name: "usr", type: "address" }],
outputs: [{ name: "", type: "uint256" }],
},
{
name: "list",
type: "function",
stateMutability: "view",
inputs: [{ name: "cdpId", type: "uint256" }],
outputs: [
{ name: "prev", type: "uint256" },
{ name: "next", type: "uint256" },
],
},
] as const;
DssProxyActions -- User-Facing API
DssProxyActions is a library contract called via delegatecall from a user's DSProxy. It bundles multi-step vault operations into single transactions.
Key functions (called through DSProxy):
open(cdpManager, ilk, dsProxy)-- create a new vaultlockETH(cdpManager, ethJoin, cdpId)-- deposit ETH collateral (payable)lockGem(cdpManager, gemJoin, cdpId, wad)-- deposit ERC-20 collateraldraw(cdpManager, jug, daiJoin, cdpId, wad)-- generate DAI from vaultwipe(cdpManager, daiJoin, cdpId, wad)-- repay DAI debtwipeAll(cdpManager, daiJoin, cdpId)-- repay all DAI debtfreeETH(cdpManager, ethJoin, cdpId, wad)-- withdraw ETH collateralfreeGem(cdpManager, gemJoin, cdpId, wad)-- withdraw ERC-20 collaterallockETHAndDraw(cdpManager, jug, ethJoin, daiJoin, cdpId, wadDai)-- lock ETH + draw DAI in one txopenLockETHAndDraw(cdpManager, jug, ethJoin, daiJoin, ilk, wadDai)-- open vault + lock ETH + draw DAI
Jug -- Stability Fee Accumulator
The Jug tracks per-ilk stability fee rates. Calling jug.drip(ilk) updates vat.ilks[ilk].rate by compounding the fee since the last update.
const jugAbi = [
{
name: "drip",
type: "function",
stateMutability: "nonpayable",
inputs: [{ name: "ilk", type: "bytes32" }],
outputs: [{ name: "", type: "uint256" }],
},
{
name: "ilks",
type: "function",
stateMutability: "view",
inputs: [{ name: "ilk", type: "bytes32" }],
outputs: [
{ name: "duty", type: "uint256" },
{ name: "rho", type: "uint256" },
],
},
] as const;
duty is the per-second stability fee rate (ray). rho is the last drip timestamp.
Join Adapters
Join adapters move tokens between the external ERC-20 world and the internal Vat accounting.
- GemJoin -- locks collateral tokens. One per collateral type.
join(urn, wad)moves tokens into the Vat.exit(usr, wad)withdraws them. - DaiJoin -- converts between internal rad-denominated DAI and external ERC-20 DAI.
join(urn, wad)burns ERC-20 DAI and credits internal DAI.exit(usr, wad)mints ERC-20 DAI from internal DAI. - ETHJoin -- special join adapter that wraps native ETH into the Vat (no ERC-20 needed).
Opening a Vault via DSProxy
The standard flow for opening a vault and generating DAI:
import {
createPublicClient,
createWalletClient,
http,
parseEther,
encodeFunctionData,
type Address,
} from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { mainnet } from "viem/chains";
const publicClient = createPublicClient({
chain: mainnet,
transport: http(process.env.RPC_URL),
});
const account = privateKeyToAccount(
process.env.PRIVATE_KEY as `0x${string}`
);
const walletClient = createWalletClient({
account,
chain: mainnet,
transport: http(process.env.RPC_URL),
});
const CDP_MANAGER = "0x5ef30b9986345249bc32d8928B7ee64DE9435E39" as const;
const MCD_JUG = "0x19c0976f590D67707E62397C87829d896Dc0f1F1" as const;
const MCD_JOIN_ETH_A = "0x2F0b23f53734252Bda2277357e97e1517d6B042A" as const;
const MCD_JOIN_DAI = "0x9759A6Ac90977b93B58547b4A71c78317f391A28" as const;
const PROXY_ACTIONS = "0x82ecD135Dce65Fbc6DbdD0e4237E0AF93FFD5038" as const;
// ETH-A ilk identifier (bytes32)
const ETH_A_ILK = "0x4554482d41000000000000000000000000000000000000000000000000000000" as const;
const proxyActionsAbi = [
{
name: "openLockETHAndDraw",
type: "function",
stateMutability: "payable",
inputs: [
{ name: "manager", type: "address" },
{ name: "jug", type: "address" },
{ name: "ethJoin", type: "address" },
{ name: "daiJoin", type: "address" },
{ name: "ilk", type: "bytes32" },
{ name: "wadD", type: "uint256" },
],
outputs: [{ name: "cdp", type: "uint256" }],
},
{
name: "lockETHAndDraw",
type: "function",
stateMutability: "payable",
inputs: [
{ name: "manager", type: "address" },
{ name: "jug", type: "address" },
{ name: "ethJoin", type: "address" },
{ name: "daiJoin", type: "address" },
{ name: "cdp", type: "uint256" },
{ name: "wadD", type: "uint256" },
],
outputs: [],
},
{
name: "wipeAllAndFreeETH",
type: "function",
stateMutability: "nonpayable",
inputs: [
{ name: "manager", type: "address" },
{ name: "ethJoin", type: "address" },
{ name: "daiJoin", type: "address" },
{ name: "cdp", type: "uint256" },
{ name: "wadC", type: "uint256" },
],
outputs: [],
},
] as const;
const dsProxyAbi = [
{
name: "execute",
type: "function",
stateMutability: "payable",
inputs: [
{ name: "_target", type: "address" },
{ name: "_data", type: "bytes" },
],
outputs: [{ name: "response", type: "bytes32" }],
},
] as const;
Execute via DSProxy
All DssProxyActions calls go through your DSProxy's execute(target, data):
async function openVaultAndDrawDai(
dsProxy: Address,
ethAmount: bigint,
daiAmount: bigint
): Promise<`0x${string}`> {
const calldata = encodeFunctionData({
abi: proxyActionsAbi,
functionName: "openLockETHAndDraw",
args: [CDP_MANAGER, MCD_JUG, MCD_JOIN_ETH_A, MCD_JOIN_DAI, ETH_A_ILK, daiAmount],
});
const { request } = await publicClient.simulateContract({
address: dsProxy,
abi: dsProxyAbi,
functionName: "execute",
args: [PROXY_ACTIONS, calldata],
value: ethAmount,
account: account.address,
});
const hash = await walletClient.writeContract(request);
const receipt = await publicClient.waitForTransactionReceipt({ hash });
if (receipt.status !== "success") {
throw new Error("openLockETHAndDraw reverted");
}
return hash;
}
Reading Vault State
const vatAbi = [
{
name: "ilks",
type: "function",
stateMutability: "view",
inputs: [{ name: "ilk", type: "bytes32" }],
outputs: [
{ name: "Art", type: "uint256" },
{ name: "rate", type: "uint256" },
{ name: "spot", type: "uint256" },
{ name: "line", type: "uint256" },
{ name: "dust", type: "uint256" },
],
},
{
name: "urns",
type: "function",
stateMutability: "view",
inputs: [
{ name: "ilk", type: "bytes32" },
{ name: "urn", type: "address" },
],
outputs: [
{ name: "ink", type: "uint256" },
{ name: "art", type: "uint256" },
],
},
{
name: "dai",
type: "function",
stateMutability: "view",
inputs: [{ name: "usr", type: "address" }],
outputs: [{ name: "", type: "uint256" }],
},
] as const;
const MCD_VAT = "0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B" as const;
async function getVaultInfo(cdpId: bigint) {
const [ilk, urn] = await Promise.all([
publicClient.readContract({
address: CDP_MANAGER,
abi: cdpManagerAbi,
functionName: "ilks",
args: [cdpId],
}),
publicClient.readContract({
address: CDP_MANAGER,
abi: cdpManagerAbi,
functionName: "urns",
args: [cdpId],
}),
]);
const [ilkData, urnData] = await Promise.all([
publicClient.readContract({
address: MCD_VAT,
abi: vatAbi,
functionName: "ilks",
args: [ilk],
}),
publicClient.readContract({
address: MCD_VAT,
abi: vatAbi,
functionName: "urns",
args: [ilk, urn],
}),
]);
const ink = urnData[0]; // locked collateral (wad)
const art = urnData[1]; // normalized debt (wad)
const rate = ilkData[1]; // accumulated rate (ray)
const spot = ilkData[2]; // price with safety margin (ray)
// Actual debt = art * rate (result in rad, divide by RAY for wad)
const RAY = 10n ** 27n;
const debt = (art * rate + RAY - 1n) / RAY; // round up
// Collateral value = ink * spot (result in rad, divide by RAY for wad)
const collateralValue = (ink * spot) / RAY;
return { ilk, urn, ink, art, rate, spot, debt, collateralValue };
}
DAI Savings Rate (DSR)
The DSR lets DAI holders earn yield by depositing into the Pot contract. DsrManager simplifies the Pot interaction.
const DSR_MANAGER = "0x373238337Bfe1146fb49989fc222523f83081dDb" as const;
const MCD_POT = "0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7" as const;
const dsrManagerAbi = [
{
name: "join",
type: "function",
stateMutability: "nonpayable",
inputs: [
{ name: "dst", type: "address" },
{ name: "wad", type: "uint256" },
],
outputs: [],
},
{
name: "exit",
type: "function",
stateMutability: "nonpayable",
inputs: [
{ name: "dst", type: "address" },
{ name: "wad", type: "uint256" },
],
outputs: [],
},
{
name: "exitAll",
type: "function",
stateMutability: "nonpayable",
inputs: [{ name: "dst", type: "address" }],
outputs: [],
},
{
name: "pieOf",
type: "function",
stateMutability: "view",
inputs: [{ name: "usr", type: "address" }],
outputs: [{ name: "", type: "uint256" }],
},
] as const;
const potAbi = [
{
name: "chi",
type: "function",
stateMutability: "view",
inputs: [],
outputs: [{ name: "", type: "uint256" }],
},
{
name: "dsr",
type: "function",
stateMutability: "view",
inputs: [],
outputs: [{ name: "", type: "uint256" }],
},
{
name: "rho",
type: "function",
stateMutability: "view",
inputs: [],
outputs: [{ name: "", type: "uint256" }],
},
{
name: "drip",
type: "function",
stateMutability: "nonpayable",
inputs: [],
outputs: [{ name: "", type: "uint256" }],
},
] as const;
async function getDsrInfo() {
const [dsr, chi, rho] = await Promise.all([
publicClient.readContract({
address: MCD_POT,
abi: potAbi,
functionName: "dsr",
}),
publicClient.readContract({
address: MCD_POT,
abi: potAbi,
functionName: "chi",
}),
publicClient.readContract({
address: MCD_POT,
abi: potAbi,
functionName: "rho",
}),
]);
// DSR APY = dsr^(seconds_per_year) - 1
// dsr is a per-second rate in ray (10^27)
const RAY = 10n ** 27n;
const dsrFloat = Number(dsr) / Number(RAY);
const dsrApy = (Math.pow(dsrFloat, 31536000) - 1) * 100;
return { dsr, chi, rho, dsrApy };
}
async function depositToDsr(daiAmount: bigint): Promise<`0x${string}`> {
const DAI = "0x6B175474E89094C44Da98b954EedeAC495271d0F" as const;
// Approve DsrManager to spend DAI
const approveHash = await walletClient.writeContract({
address: DAI,
abi: [
{
name: "approve",
type: "function",
stateMutability: "nonpayable",
inputs: [
{ name: "spender", type: "address" },
{ name: "amount", type: "uint256" },
],
outputs: [{ name: "", type: "bool" }],
},
] as const,
functionName: "approve",
args: [DSR_MANAGER, daiAmount],
});
const approveReceipt = await publicClient.waitForTransactionReceipt({
hash: approveHash,
});
if (approveReceipt.status !== "success") {
throw new Error("DAI approval for DSR failed");
}
// Deposit DAI into DSR
const { request } = await publicClient.simulateContract({
address: DSR_MANAGER,
abi: dsrManagerAbi,
functionName: "join",
args: [account.address, daiAmount],
account: account.address,
});
const hash = await walletClient.writeContract(request);
const receipt = await publicClient.waitForTransactionReceipt({ hash });
if (receipt.status !== "success") {
throw new Error("DSR deposit reverted");
}
return hash;
}
async function getDsrBalance(user: Address): Promise<bigint> {
const RAY = 10n ** 27n;
const [pie, chi] = await Promise.all([
publicClient.readContract({
address: DSR_MANAGER,
abi: dsrManagerAbi,
functionName: "pieOf",
args: [user],
}),
publicClient.readContract({
address: MCD_POT,
abi: potAbi,
functionName: "chi",
}),
]);
// DAI balance = pie * chi / RAY
return (pie * chi) / RAY;
}
Liquidation 2.0 (Dutch Auctions)
When a vault's collateral ratio drops below the liquidation ratio, keepers trigger liquidation via the Dog contract. The Dog starts a Dutch auction via the Clipper for that ilk.
Liquidation Flow
Dog.bark(ilk, urn, keeper)-- triggers liquidation, creates a Clipper auction- Clipper starts at a high price (using
calc-- an AbacI price calculator) - Price decreases over time according to the price curve
- Anyone calls
Clipper.take(id, amt, max, who, data)to buy collateral - Remaining collateral (if any) returns to the vault owner
const MCD_DOG = "0x135954d155898D42C90D2a57824C690e0c7BEf1B" as const;
const dogAbi = [
{
name: "bark",
type: "function",
stateMutability: "nonpayable",
inputs: [
{ name: "ilk", type: "bytes32" },
{ name: "urn", type: "address" },
{ name: "kpr", type: "address" },
],
outputs: [{ name: "id", type: "uint256" }],
},
{
name: "ilks",
type: "function",
stateMutability: "view",
inputs: [{ name: "ilk", type: "bytes32" }],
outputs: [
{ name: "clip", type: "address" },
{ name: "chop", type: "uint256" },
{ name: "hole", type: "uint256" },
{ name: "dirt", type: "uint256" },
],
},
] as const;
const clipperAbi = [
{
name: "take",
type: "function",
stateMutability: "nonpayable",
inputs: [
{ name: "id", type: "uint256" },
{ name: "amt", type: "uint256" },
{ name: "max", type: "uint256" },
{ name: "who", type: "address" },
{ name: "data", type: "bytes" },
],
outputs: [],
},
{
name: "sales",
type: "function",
stateMutability: "view",
inputs: [{ name: "id", type: "uint256" }],
outputs: [
{ name: "pos", type: "uint256" },
{ name: "tab", type: "uint256" },
{ name: "lot", type: "uint256" },
{ name: "usr", type: "address" },
{ name: "tic", type: "uint96" },
{ name: "top", type: "uint256" },
],
},
{
name: "getStatus",
type: "function",
stateMutability: "view",
inputs: [{ name: "id", type: "uint256" }],
outputs: [
{ name: "needsRedo", type: "bool" },
{ name: "price", type: "uint256" },
{ name: "lot", type: "uint256" },
{ name: "tab", type: "uint256" },
],
},
{
name: "count",
type: "function",
stateMutability: "view",
inputs: [],
outputs: [{ name: "", type: "uint256" }],
},
{
name: "list",
type: "function",
stateMutability: "view",
inputs: [],
outputs: [{ name: "", type: "uint256[]" }],
},
] as const;
Participating in a Dutch Auction
async function takeFromAuction(
clipperAddress: Address,
auctionId: bigint,
collateralAmount: bigint,
maxPrice: bigint
): Promise<`0x${string}`> {
// Check auction status
const status = await publicClient.readContract({
address: clipperAddress,
abi: clipperAbi,
functionName: "getStatus",
args: [auctionId],
});
const [needsRedo, currentPrice, lot, tab] = status;
if (needsRedo) {
throw new Error("Auction needs redo -- price has gone stale");
}
if (currentPrice > maxPrice) {
throw new Error(
`Current price ${currentPrice} exceeds max ${maxPrice}. Wait for price to decrease.`
);
}
if (lot === 0n || tab === 0n) {
throw new Error("Auction is complete -- no collateral remaining");
}
// take() requires DAI approval to the Vat (internal DAI)
// Keepers typically pre-approve the Clipper in the Vat
const { request } = await publicClient.simulateContract({
address: clipperAddress,
abi: clipperAbi,
functionName: "take",
args: [auctionId, collateralAmount, maxPrice, account.address, "0x"],
account: account.address,
});
const hash = await walletClient.writeContract(request);
const receipt = await publicClient.waitForTransactionReceipt({ hash });
if (receipt.status !== "success") {
throw new Error("Auction take reverted");
}
return hash;
}
MKR Governance
MKR holders vote on protocol parameters through the Chief contract. The voting flow uses a delegate + hat pattern.
Executive Voting
Executive votes change live protocol parameters. They are spell contracts that are cast when enough MKR is staked on them.
const MCD_GOV = "0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2" as const; // MKR token
const MCD_ADM = "0x0a3f6849f78076aefaDf113F5BED87720274dDC0" as const; // DSChief
const chiefAbi = [
{
name: "vote",
type: "function",
stateMutability: "nonpayable",
inputs: [{ name: "yays", type: "address[]" }],
outputs: [{ name: "", type: "bytes32" }],
},
{
name: "lock",
type: "function",
stateMutability: "nonpayable",
inputs: [{ name: "wad", type: "uint256" }],
outputs: [],
},
{
name: "free",
type: "function",
stateMutability: "nonpayable",
inputs: [{ name: "wad", type: "uint256" }],
outputs: [],
},
{
name: "hat",
type: "function",
stateMutability: "view",
inputs: [],
outputs: [{ name: "", type: "address" }],
},
{
name: "approvals",
type: "function",
stateMutability: "view",
inputs: [{ name: "candidate", type: "address" }],
outputs: [{ name: "", type: "uint256" }],
},
{
name: "deposits",
type: "function",
stateMutability: "view",
inputs: [{ name: "usr", type: "address" }],
outputs: [{ name: "", type: "uint256" }],
},
] as const;
Governance Flow
- Lock MKR in Chief:
chief.lock(amount) - Vote for a spell:
chief.vote([spellAddress]) - If the spell gets the most MKR, it becomes the
hat - Anyone can
liftthe hat to make it the active authority - The spell is
castto execute parameter changes
Sky Protocol Rebranding
MakerDAO rebranded to Sky Protocol in 2024. New tokens:
- USDS -- upgraded DAI (1:1 convertible)
- SKY -- upgraded MKR (1 MKR = 24,000 SKY)
- sUSDS -- USDS savings token (ERC-4626), replaces DSR for USDS holders
Token Migration
const DAI = "0x6B175474E89094C44Da98b954EedeAC495271d0F" as const;
const USDS = "0xdC035D45d973E3EC169d2276DDab16f1e407384F" as const;
const MKR = "0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2" as const;
const SKY = "0x56072C95FAA7932F4D8Aa042BE0611d2a2CE73a5" as const;
const DAI_USDS = "0x3225737a9Bbb6473CB4a45b7244ACa2BeFdB276A" as const; // DaiUsds converter
const MKR_SKY = "0xBDcFCA946b6CDd965f99a839e4435Bcdc1bc470B" as const; // MkrSky converter
const SUSDS = "0xa3931d71877C0E7a3148CB7Eb4463524FEc27fbD" as const; // sUSDS vault
const daiUsdsAbi = [
{
name: "daiToUsds",
type: "function",
stateMutability: "nonpayable",
inputs: [
{ name: "usr", type: "address" },
{ name: "wad", type: "uint256" },
],
outputs: [],
},
{
name: "usdsToDai",
type: "function",
stateMutability: "nonpayable",
inputs: [
{ name: "usr", type: "address" },
{ name: "wad", type: "uint256" },
],
outputs: [],
},
] as const;
const mkrSkyAbi = [
{
name: "mkrToSky",
type: "function",
stateMutability: "nonpayable",
inputs: [
{ name: "usr", type: "address" },
{ name: "mkrAmt", type: "uint256" },
],
outputs: [],
},
{
name: "skyToMkr",
type: "function",
stateMutability: "nonpayable",
inputs: [
{ name: "usr", type: "address" },
{ name: "skyAmt", type: "uint256" },
],
outputs: [],
},
{
name: "rate",
type: "function",
stateMutability: "view",
inputs: [],
outputs: [{ name: "", type: "uint256" }],
},
] as const;
// sUSDS is an ERC-4626 vault for USDS savings
const susdsAbi = [
{
name: "deposit",
type: "function",
stateMutability: "nonpayable",
inputs: [
{ name: "assets", type: "uint256" },
{ name: "receiver", type: "address" },
],
outputs: [{ name: "shares", type: "uint256" }],
},
{
name: "withdraw",
type: "function",
stateMutability: "nonpayable",
inputs: [
{ name: "assets", type: "uint256" },
{ name: "receiver", type: "address" },
{ name: "owner", type: "address" },
],
outputs: [{ name: "shares", type: "uint256" }],
},
{
name: "redeem",
type: "function",
stateMutability: "nonpayable",
inputs: [
{ name: "shares", type: "uint256" },
{ name: "receiver", type: "address" },
{ name: "owner", type: "address" },
],
outputs: [{ name: "assets", type: "uint256" }],
},
{
name: "convertToAssets",
type: "function",
stateMutability: "view",
inputs: [{ name: "shares", type: "uint256" }],
outputs: [{ name: "", type: "uint256" }],
},
{
name: "convertToShares",
type: "function",
stateMutability: "view",
inputs: [{ name: "assets", type: "uint256" }],
outputs: [{ name: "", type: "uint256" }],
},
{
name: "totalAssets",
type: "function",
stateMutability: "view",
inputs: [],
outputs: [{ name: "", type: "uint256" }],
},
{
name: "balanceOf",
type: "function",
stateMutability: "view",
inputs: [{ name: "account", type: "address" }],
outputs: [{ name: "", type: "uint256" }],
},
] as const;
Upgrading DAI to USDS
async function upgradeDaiToUsds(amount: bigint): Promise<`0x${string}`> {
// Approve DaiUsds converter to spend DAI
const approveHash = await walletClient.writeContract({
address: DAI,
abi: [
{
name: "approve",
type: "function",
stateMutability: "nonpayable",
inputs: [
{ name: "spender", type: "address" },
{ name: "amount", type: "uint256" },
],
outputs: [{ name: "", type: "bool" }],
},
] as const,
functionName: "approve",
args: [DAI_USDS, amount],
});
const approveReceipt = await publicClient.waitForTransactionReceipt({
hash: approveHash,
});
if (approveReceipt.status !== "success") {
throw new Error("DAI approval for upgrade failed");
}
// Convert DAI -> USDS (1:1)
const { request } = await publicClient.simulateContract({
address: DAI_USDS,
abi: daiUsdsAbi,
functionName: "daiToUsds",
args: [account.address, amount],
account: account.address,
});
const hash = await walletClient.writeContract(request);
const receipt = await publicClient.waitForTransactionReceipt({ hash });
if (receipt.status !== "success") {
throw new Error("DAI to USDS conversion reverted");
}
return hash;
}
USDS Savings Rate (sUSDS)
async function depositToSusds(usdsAmount: bigint): Promise<{
hash: `0x${string}`;
shares: bigint;
}> {
// Approve sUSDS vault to spend USDS
const approveHash = await walletClient.writeContract({
address: USDS,
abi: [
{
name: "approve",
type: "function",
stateMutability: "nonpayable",
inputs: [
{ name: "spender", type: "address" },
{ name: "amount", type: "uint256" },
],
outputs: [{ name: "", type: "bool" }],
},
] as const,
functionName: "approve",
args: [SUSDS, usdsAmount],
});
const approveReceipt = await publicClient.waitForTransactionReceipt({
hash: approveHash,
});
if (approveReceipt.status !== "success") {
throw new Error("USDS approval for sUSDS failed");
}
// Deposit USDS into sUSDS vault
const { request, result } = await publicClient.simulateContract({
address: SUSDS,
abi: susdsAbi,
functionName: "deposit",
args: [usdsAmount, account.address],
account: account.address,
});
const hash = await walletClient.writeContract(request);
const receipt = await publicClient.waitForTransactionReceipt({ hash });
if (receipt.status !== "success") {
throw new Error("sUSDS deposit reverted");
}
return { hash, shares: result };
}
Spark Protocol
Spark Protocol is an Aave V3 fork maintained by the Maker/Sky ecosystem. It uses DAI/USDS as its primary lending asset with preferential rates backed by the Maker D3M (Direct Deposit Module).
Key difference from vanilla Aave V3: Spark has a direct credit line from Maker, so DAI/USDS liquidity is deep and rates are governance-controlled.
Spark uses standard Aave V3 interfaces -- see the Aave skill for integration patterns. The Pool contract address for Spark on Ethereum mainnet is 0xC13e21B648A5Ee794902342038FF3aDAB66BE987.
DSProxy Setup
Most users need a DSProxy before interacting with Maker Vaults. The ProxyRegistry creates one per address.
const PROXY_REGISTRY = "0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4" as const;
const proxyRegistryAbi = [
{
name: "build",
type: "function",
stateMutability: "nonpayable",
inputs: [],
outputs: [{ name: "proxy", type: "address" }],
},
{
name: "proxies",
type: "function",
stateMutability: "view",
inputs: [{ name: "owner", type: "address" }],
outputs: [{ name: "", type: "address" }],
},
] as const;
async function getOrCreateProxy(): Promise<Address> {
const existing = await publicClient.readContract({
address: PROXY_REGISTRY,
abi: proxyRegistryAbi,
functionName: "proxies",
args: [account.address],
});
const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000" as Address;
if (existing !== ZERO_ADDRESS) {
return existing;
}
const { request } = await publicClient.simulateContract({
address: PROXY_REGISTRY,
abi: proxyRegistryAbi,
functionName: "build",
account: account.address,
});
const hash = await walletClient.writeContract(request);
const receipt = await publicClient.waitForTransactionReceipt({ hash });
if (receipt.status !== "success") {
throw new Error("DSProxy creation reverted");
}
const proxyAddress = await publicClient.readContract({
address: PROXY_REGISTRY,
abi: proxyRegistryAbi,
functionName: "proxies",
args: [account.address],
});
return proxyAddress;
}
Common Patterns
Calculate Vault Collateralization Ratio
async function getCollateralizationRatio(cdpId: bigint): Promise<{
ratio: number;
isUnsafe: boolean;
}> {
const vault = await getVaultInfo(cdpId);
const RAY = 10n ** 27n;
if (vault.art === 0n) {
return { ratio: Infinity, isUnsafe: false };
}
// debt = art * rate (in rad), collateralValue = ink * spot (in rad)
const debt = vault.art * vault.rate;
const collateralValue = vault.ink * vault.spot;
if (debt === 0n) {
return { ratio: Infinity, isUnsafe: false };
}
const ratio = Number(collateralValue * 10000n / debt) / 100;
const isUnsafe = collateralValue < debt;
return { ratio, isUnsafe };
}
Encode Ilk Name
import { toHex, padHex } from "viem";
function encodeIlk(name: string): `0x${string}` {
return padHex(toHex(name), { size: 32, dir: "right" });
}
// encodeIlk("ETH-A") = 0x4554482d41000000000000000000000000000000000000000000000000000000
List User's Vaults
async function listUserVaults(user: Address): Promise<bigint[]> {
const count = await publicClient.readContract({
address: CDP_MANAGER,
abi: cdpManagerAbi,
functionName: "count",
args: [user],
});
if (count === 0n) return [];
const first = await publicClient.readContract({
address: CDP_MANAGER,
abi: cdpManagerAbi,
functionName: "first",
args: [user],
});
const vaults: bigint[] = [first];
let current = first;
for (let i = 1n; i < count; i++) {
const [, next] = await publicClient.readContract({
address: CDP_MANAGER,
abi: cdpManagerAbi,
functionName: "list",
args: [current],
});
if (next === 0n) break;
vaults.push(next);
current = next;
}
return vaults;
}
Security Considerations
- Dust limit: Every vault must maintain at least
dustamount of debt (or zero debt). Partial repayments that leave debt below dust will revert. - Oracle delay: Maker uses OSM (Oracle Security Module) which delays price updates by 1 hour. This means liquidations use prices that are up to 1 hour old.
- Liquidation penalty: The
chopparameter (typically 13%) is added on top of the debt during liquidation. Maintain safe collateralization ratios. - DSProxy ownership: Your DSProxy is a smart contract wallet. If you lose access, you lose control of all vaults owned by that proxy.
- Governance attacks: The Chief contract is vulnerable to flash loan governance attacks. The GSM (Governance Security Module) imposes a 48-hour delay on spell execution.