当前位置: 首页 > Skill >

Polygon PoS Development

Polygon PoS Development

Polygon PoS Development

{"answer":"Polygon PoS开发指南:支持Foundry框架(含部署与测试策略),适用于Polygon合约部署、Amoy测试网测试、领水及Polygonscan验约。"}

1.0.0 2026.11.24 607
获取Skill文件查看使用说明
作 者:沈言 许可证: 更新时间:2026.11.24
本文目录展开

Polygon PoS Development

End-to-end guide for developing and deploying smart contracts on Polygon PoS blockchain using Foundry.

Overview

Polygon PoS is an EVM-compatible Proof-of-Stake sidechain for Ethereum with:

  • Low transaction costs (fraction of a cent)
  • Fast block times (~2 seconds)
  • High throughput (65,000+ TPS theoretical)
  • Full Ethereum tooling compatibility
  • POL token for gas fees

Default Network: Amoy Testnet (Chain ID: 80002) - Use for all testing before mainnet.

🚀 Quick Navigation

For Agents/Fast Deployment: Jump to Quick Start Path (5-10 min)

For Production/Thorough Testing: Jump to Complete Development Path (30-60 min)

For Reference: See sections below for Network Configuration, Faucets, Troubleshooting

Two Development Paths

Choose based on your needs:

Aspect Quick Start Path Complete Development Path
Time 5-10 minutes 30-60 minutes
Best for Prototypes, demos, simple contracts Production, complex systems, mainnet
Testing Basic compilation check Unit tests, integration tests, fork tests
Scripts Used None (direct forge commands) Direct forge commands with all options
Documentation Minimal Full reference guides
Verification Automatic during deploy Multiple methods with troubleshooting
Agent-Friendly ✅ Optimized for speed ⚠️ Comprehensive but slower

Path 1: Quick Start (Minimal Time - Agent-Friendly)

Best for: Fast deployment, simple contracts, prototyping Time: 5-10 minutes What you get: Contract deployed and verified on testnet

Skip to Quick Start Path below.

Path 2: Complete Guide (Full Development Workflow)

Best for: Production contracts, complex systems, thorough testing Time: 30-60 minutes What you get: Fully tested, optimized, and production-ready deployment

Skip to Complete Development Path below.

Quick Start Path

Goal: Deploy a contract to Polygon Amoy testnet in minimal steps.

Prerequisites

  • Foundry installed: curl -L https://foundry.paradigm.xyz | bash && foundryup
  • Wallet with private key
  • Polygonscan API key (get from https://polygonscan.com/myapikey)

Step 1: Create Project (30 seconds)

forge init my-polygon-project
cd my-polygon-project

Step 2: Configure Environment (1 minute)

Create .env file:

PRIVATE_KEY=your_private_key_without_0x_prefix

Step 3: Get Testnet Tokens (2 minutes)

Visit: https://www.alchemy.com/faucets/polygon-amoy

  • Paste your wallet address
  • Claim 0.2-0.5 POL (no signup needed)

Step 4: Deploy (1 minute)

# Deploy to Amoy testnet
forge script script/Counter.s.sol:CounterScript 
    --rpc-url https://rpc-amoy.polygon.technology 
    --private-key $PRIVATE_KEY 
    --broadcast

Done! Your contract is deployed and verified on Amoy testnet.

View at: https://amoy.polygonscan.com/address/YOUR_CONTRACT_ADDRESS

Complete Development Path

Goal: Production-ready deployment with comprehensive testing and optimization.

Phase 1: Setup (5 minutes)

  1. Install Foundry:
curl -L https://foundry.paradigm.xyz | bash
foundryup
  1. Initialize Project:
forge init my-polygon-project
cd my-polygon-project
  1. Configure for Polygon:

Update foundry.toml with Polygon settings:

[profile.default]
src = "src"
out = "out"
libs = ["lib"]
solc_version = "0.8.24"
optimizer = true
optimizer_runs = 200

[rpc_endpoints]
amoy = "https://rpc-amoy.polygon.technology"
polygon = "https://polygon-rpc.com"

[etherscan]
amoy = { key = "${POLYGONSCAN_API_KEY}", url = "https://api-amoy.polygonscan.com/api" }
polygon = { key = "${POLYGONSCAN_API_KEY}", url = "https://api.polygonscan.com/api" }
  1. Setup Environment:

Create .env file:

PRIVATE_KEY=your_private_key
WALLET_ADDRESS=0xYourAddress
POLYGONSCAN_API_KEY=your_api_key

Phase 2: Write & Test Contracts (10-20 minutes)

  1. Write Contract (or use assets/sample-contracts/HelloWorld.sol as template)

  2. Write Tests:

// test/MyContract.t.sol
import "forge-std/Test.sol";
import "../src/MyContract.sol";

contract MyContractTest is Test {
    MyContract public myContract;
    
    function setUp() public {
        myContract = new MyContract();
    }
    
    function testDeployment() public {
        assertEq(myContract.owner(), address(this));
    }
}
  1. Run Tests:
forge test -vvv                    # Run tests
forge test --gas-report            # Check gas usage
forge coverage                     # Check coverage
  1. Fork Testing (optional):
# Test against real Polygon state
forge test --fork-url https://polygon-rpc.com

See references/testing-strategies.md for comprehensive testing patterns.

Phase 3: Get Testnet Tokens (2-5 minutes)

Visit one of these faucets:

Alchemy (recommended - no auth): https://www.alchemy.com/faucets/polygon-amoy QuickNode: https://faucet.quicknode.com/polygon/amoy GetBlock: https://getblock.io/faucet/matic-amoy/ Chainlink: https://faucets.chain.link/polygon-amoy LearnWeb3: https://learnweb3.io/faucets/polygon_amoy/

Phase 4: Deploy to Testnet (2-5 minutes)

forge script script/Deploy.s.sol 
    --rpc-url amoy 
    --private-key $PRIVATE_KEY 
    --broadcast 
    --verify 
    --etherscan-api-key $POLYGONSCAN_API_KEY

Create a deployment script in script/Deploy.s.sol:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "forge-std/Script.sol";
import "../src/YourContract.sol";

contract DeployScript is Script {
    function run() external {
        uint256 deployerPrivateKey = vm.envUint("PRIVATE_KEY");
        
        vm.startBroadcast(deployerPrivateKey);
        
        // Deploy your contract
        YourContract yourContract = new YourContract();
        
        vm.stopBroadcast();
        
        console.log("Contract deployed to:", address(yourContract));
    }
}

See references/foundry-deployment.md for advanced deployment patterns.

Phase 5: Verify Contract (1-2 minutes)

If not verified during deployment:

forge verify-contract 
    CONTRACT_ADDRESS 
    src/MyContract.sol:MyContract 
    --chain-id 80002 
    --etherscan-api-key $POLYGONSCAN_API_KEY

See references/contract-verification.md for troubleshooting verification issues.

Phase 6: Test on Testnet (5-10 minutes)

  1. View on Explorer: https://amoy.polygonscan.com/address/CONTRACT_ADDRESS
  2. Interact with Contract: Use cast or web interface
  3. Test All Functions: Verify behavior matches expectations
  4. Monitor Gas Costs: Check if optimization needed

Phase 7: Deploy to Mainnet (5 minutes)

⚠️ IMPORTANT: Complete mainnet deployment checklist first!

See Mainnet Deployment Checklist below.

forge script script/Deploy.s.sol 
    --rpc-url polygon 
    --private-key $PRIVATE_KEY 
    --broadcast 
    --verify 
    --etherscan-api-key $POLYGONSCAN_API_KEY

End of Complete Development Path ✅

Network Configuration

Amoy Testnet (Recommended for Testing)

Property Value
Network Name Polygon Amoy
Chain ID 80002
Currency POL
RPC URL https://rpc-amoy.polygon.technology
WebSocket wss://polygon-amoy.drpc.org
Explorer https://amoy.polygonscan.com
Faucets Multiple (see below)

Polygon Mainnet

Property Value
Network Name Polygon
Chain ID 137
Currency POL
RPC URL https://polygon-rpc.com
WebSocket wss://polygon.drpc.org
Explorer https://polygonscan.com

Getting Testnet Tokens

Multiple faucets available for Amoy testnet POL tokens.

Quick Access

Run the faucet helper script:

./scripts/get-testnet-tokens.sh

Available Faucets

Alchemy Faucet (Recommended - No auth required)

  • URL: https://www.alchemy.com/faucets/polygon-amoy
  • Amount: 0.5 POL/day (with account), 0.2 POL/day (without)
  • Requirements: None

QuickNode Faucet

  • URL: https://faucet.quicknode.com/polygon/amoy
  • Amount: 0.1 POL/day (2x with tweet)
  • Requirements: Connect wallet

GetBlock Faucet

  • URL: https://getblock.io/faucet/matic-amoy/
  • Amount: 0.1 POL/day
  • Requirements: Login

Chainlink Faucet

  • URL: https://faucets.chain.link/polygon-amoy
  • Amount: 0.1 POL/day
  • Requirements: GitHub auth

LearnWeb3 Faucet

  • URL: https://learnweb3.io/faucets/polygon_amoy/
  • Amount: 0.1 POL/day
  • Requirements: GitHub auth

Tips:

  • Most faucets limit to 1 request per 24 hours
  • If rate-limited, try a different faucet
  • Some offer bonus tokens for tweeting

Deployment Workflow

Environment Setup

Create .env file (see assets/sample-contracts/.env.example):

PRIVATE_KEY=your_private_key_here
WALLET_ADDRESS=0xYourAddress
POLYGONSCAN_API_KEY=your_api_key_here

Add to .gitignore:

.env
broadcast/
deployments/

Deploy to Testnet

Option 1: Use helper script (recommended)

./scripts/deploy-foundry.sh

Option 2: Manual deployment

forge script script/Deploy.s.sol 
    --rpc-url amoy 
    --private-key $PRIVATE_KEY 
    --broadcast 
    --verify

Option 3: Deploy without verification

forge script script/Deploy.s.sol 
    --rpc-url amoy 
    --private-key $PRIVATE_KEY 
    --broadcast

Deploy to Mainnet

⚠️ IMPORTANT: Test thoroughly on Amoy first!

# Use deployment script and select mainnet option
./scripts/deploy-foundry.sh

For detailed deployment patterns, see references/foundry-deployment.md.

Testing Strategies

Local Testing

Write tests in test/ directory:

// test/MyContract.t.sol
import "forge-std/Test.sol";
import "../src/MyContract.sol";

contract MyContractTest is Test {
    MyContract public myContract;
    
    function setUp() public {
        myContract = new MyContract();
    }
    
    function testFunction() public {
        // Test logic
    }
}

Run tests:

forge test              # Run all tests
forge test -vvv         # Verbose output
forge test --gas-report # Show gas usage

Fork Testing

Test against real Polygon state:

forge test --fork-url https://polygon-rpc.com

Testnet Testing

Deploy to Amoy and test with real transactions. See references/testing-strategies.md for comprehensive testing patterns.

Contract Verification

Verification makes your contract code public and trustworthy.

During Deployment (Recommended)

forge script script/Deploy.s.sol 
    --rpc-url amoy 
    --private-key $PRIVATE_KEY 
    --broadcast 
    --verify 
    --etherscan-api-key $POLYGONSCAN_API_KEY

After Deployment

Option 1: Use helper script

./scripts/verify-contract.sh

Option 2: Manual verification

forge verify-contract 
    CONTRACT_ADDRESS 
    src/MyContract.sol:MyContract 
    --chain-id 80002 
    --etherscan-api-key $POLYGONSCAN_API_KEY 
    --verifier-url https://api-amoy.polygonscan.com/api

With Constructor Arguments

forge verify-contract 
    CONTRACT_ADDRESS 
    src/MyContract.sol:MyContract 
    --chain-id 80002 
    --etherscan-api-key $POLYGONSCAN_API_KEY 
    --constructor-args $(cast abi-encode "constructor(address,uint256)" 0x123... 1000)

For troubleshooting verification issues, see references/contract-verification.md.

Common Workflows

Which Path Should I Use?

Use Quick Start Path when:

  • You need fast deployment (prototyping, demos)
  • Contract is simple and low-risk
  • You're an AI agent with limited time
  • Testing is minimal or done elsewhere

Use Complete Development Path when:

  • Deploying to mainnet
  • Contract handles real value
  • Complex logic requiring thorough testing
  • Team collaboration and code review needed
  • Security is critical

Mainnet Deployment Checklist

Before deploying to mainnet:

  • All tests passing (forge test)
  • Deployed and tested on Amoy testnet
  • Contract verified on Amoy
  • Security review completed
  • Gas optimization done
  • Documentation complete
  • Constructor arguments double-checked
  • Sufficient POL in wallet for gas
  • Deployment script tested
  • Team notified of deployment

Sample Contract Pattern

Example smart contract structure for Polygon:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

contract HelloWorld {
    address public owner;
    string public message;
    uint256 public updateCount;
    
    event MessageUpdated(address indexed updater, string newMessage);
    
    error NotOwner();
    error EmptyMessage();
    
    constructor(string memory initialMessage) {
        owner = msg.sender;
        message = initialMessage;
    }
    
    modifier onlyOwner() {
        if (msg.sender != owner) revert NotOwner();
        _;
    }
    
    function setMessage(string calldata newMessage) external {
        if (bytes(newMessage).length == 0) revert EmptyMessage();
        message = newMessage;
        updateCount++;
        emit MessageUpdated(msg.sender, newMessage);
    }
}

Key patterns:

  • Use custom errors instead of require strings (gas-efficient)
  • Emit events for important state changes
  • Use modifiers for access control
  • Optimize for Polygon's low gas costs

Safety Rules

  1. Test First: Always test on Amoy before mainnet
  2. Never Commit Keys: Add .env to .gitignore
  3. Verify Contracts: Always verify for transparency
  4. Check Network: Double-check chain ID before deployment
  5. Sufficient Balance: Ensure enough POL for gas
  6. Save Addresses: Document deployed contract addresses
  7. Audit Code: Security review before mainnet
  8. Use Scripts: Automate deployments to reduce errors
  9. Backup Keys: Securely backup private keys
  10. Test Verification: Verify contracts on testnet first

Troubleshooting

Insufficient Funds for Gas

Error: insufficient funds for gas * price + value

Solution: Get testnet POL from faucets (run ./scripts/get-testnet-tokens.sh)

Contract Not Found

Error: src/MyContract.sol:MyContract not found

Solution: Check file path and contract name match exactly

RPC Connection Issues

Error: failed to get chain id

Solution:

  • Check internet connection
  • Try alternative RPC URL
  • Use dedicated RPC provider (Alchemy, QuickNode)

Verification Failed

Error: bytecode does not match

Solution:

  • Wait 1-2 minutes for contract to be indexed
  • Check constructor arguments are correct
  • Verify compiler settings match deployment

Gas Estimation Failed

Error: gas estimation failed

Solution:

  • Check contract logic for reverts
  • Ensure sufficient balance
  • Check function parameters

Resources

Foundry Documentation

  • Book: https://book.getfoundry.sh/
  • GitHub: https://github.com/foundry-rs/foundry

Polygon Documentation

  • Docs: https://docs.polygon.technology/
  • Gas Station: https://gasstation.polygon.technology/
  • Faucets: https://faucet.polygon.technology/

Block Explorers

  • Amoy: https://amoy.polygonscan.com
  • Mainnet: https://polygonscan.com

RPC Providers

  • Alchemy: https://www.alchemy.com/
  • QuickNode: https://www.quicknode.com/
  • Infura: https://infura.io/

Community

  • Discord: https://discord.com/invite/0xPolygonCommunity
  • Telegram: https://t.me/polygonhq

Reference Files

For detailed information:

  • references/foundry-deployment.md - Complete deployment guide
  • references/testing-strategies.md - Testing best practices
  • references/contract-verification.md - Verification troubleshooting

Scripts

推荐文章

更多
PHP时间戳与日期字符串相互转换方法详解

本文介绍PHP中时间数值(Unix时间戳)与日期字符串之间的相互转换方法。通过strtotime和date函数,实现将当前时间、指定日期转换为时间戳,以及将时间戳格式化为可读的日期时间字符串,并提供相关在线计算工具推荐。

2025.11.30 1,036
PHP日期转时间戳时区偏差怎么解决

在 PHP 中将日期字符串转换为时间戳时,若未显式指定时区,默认使用脚本配置的 date.timezone 或系统时区。当服务器时区与业务逻辑预期(如 UTC )不一致时,会产生偏差。解决核心是确保输入字符串携带明确时区信息,或在转换前统一设置时区上下文。

2026.10.24 1,031
JavaScript中利用replace结合正则实现replaceAll效果

JavaScript原生仅支持replace()进行单次或全局替换,缺乏类似Java的replaceAll()便捷方法。本文总结四种在JS中实现全量替换的方案:使用带g标志的正则、带gm标志的正则、扩展String原型以及split后join。通过对比代码示例,展示各方法的实现细节与适用场景,帮助开发者根据需求选择最优解。

2025.04.29 1,020
PHP跨域配置:怎么安全地允许指定域名而非使用通配符

在 PHP 中安全地允许指定域名跨域,核心是解析请求头中的 Origin ,验证其是否在白名单内,然后动态设置 Access-Control-Allow-Origin 响应头。不要使用通配符 * ,也不要硬编码单一域名。

2025.03.29 1,019
PHP实现基础文件上传:HTML表单与$_FILES处理流程

在 HTML 表单中设置 enctype="multipart/form-data" ,并在 PHP 后端通过 $_FILES 数组接收文件,调用 move_uploaded_file() 将临时文件移动到目标目录即可完成上传。

2026.09.07 1,016
OpenAI的Jalapeno芯片未落地,教你分辨300兆瓦算力消息

OpenAI计划在SB Energy租赁的数据中心部署约300兆瓦自研Jalapeno推理芯片,但目前双方仍处于洽谈阶段,交易细节与上线时间表均未公布。本文带你按报道原文核实项目所处阶段,厘清芯片发布、电力功率与实际推理算力的边界,并将融资意向与签约、开工、投运节点分开追踪,避免误将规划容量计入现有算力。

2026.12.02 1,014
Skill 文件
  • SKILL.md
    • Polygon PoS Development
    • Overview
    • 🚀 Quick Navigation
    • Two Development Paths
      • Path 1: Quick Start (Minimal Time - Agent-Friendly)
      • Path 2: Complete Guide (Full Development Workflow)
    • Quick Start Path
      • Prerequisites
      • Step 1: Create Project (30 seconds)
      • Step 2: Configure Environment (1 minute)
      • Step 3: Get Testnet Tokens (2 minutes)
      • Step 4: Deploy (1 minute)
    • Complete Development Path
      • Phase 1: Setup (5 minutes)
      • Phase 2: Write & Test Contracts (10-20 minutes)
      • Phase 3: Get Testnet Tokens (2-5 minutes)
      • Phase 4: Deploy to Testnet (2-5 minutes)
      • Phase 5: Verify Contract (1-2 minutes)
      • Phase 6: Test on Testnet (5-10 minutes)
      • Phase 7: Deploy to Mainnet (5 minutes)
    • Network Configuration
      • Amoy Testnet (Recommended for Testing)
      • Polygon Mainnet
    • Getting Testnet Tokens
      • Quick Access
      • Available Faucets
    • Deployment Workflow
      • Environment Setup
      • Deploy to Testnet
      • Deploy to Mainnet
    • Testing Strategies
      • Local Testing
      • Fork Testing
      • Testnet Testing
    • Contract Verification
      • During Deployment (Recommended)
      • After Deployment
      • With Constructor Arguments
    • Common Workflows
      • Which Path Should I Use?
      • Mainnet Deployment Checklist
    • Sample Contract Pattern
    • Safety Rules
    • Troubleshooting
      • Insufficient Funds for Gas
      • Contract Not Found
      • RPC Connection Issues
      • Verification Failed
      • Gas Estimation Failed
    • Resources
    • Reference Files
    • Scripts
  • 项目或源文件

相关 Skill

更多
service-qa-coach service-qa-coach Review support quality for chat, email, phone, social DM, or marketplace service teams. Use when a team needs a QA scorecard, failure-mode analysis, coaching plan, calibration checklist, or service-improvement brief without live ticketing, CRM, or contact-center system access.
高中数学作业批改助手 高中数学作业批改助手 >图片识别 直接读取学生手写作答照片,识别公式、符号、步骤 🧮 自动推导 根据题目自动生成参考答案和评分细则,无需教师预设 📊 逐步给分 每个关键步骤独立评分,体现过程分 📝 结构化报告 输出含识别内容、参考答案、逐步评分、改进建议的完整报告 🗂 批量批改 支持一次性批改多道题,最终汇总得分表
Vibration Analysis Vibration Analysis 分析来自CMS趋势、RMS/峰值、频谱及SCADA报警的风机传动链(主轴、齿轮箱、发电机)振动数据。
Traditional Bone Tool Making Basics Traditional Bone Tool Making Basics Use when you need custom, durable, repairable tools like awls, needles, scrapers, harpoons, or fishing hooks made from local animal bones or antlers and comm...
音频混音工具 音频混音工具 名称:Sound Mixing Tool(标识 sound-mixing-tool) 短简介(≤60字):音乐/音效响度精确对齐 + 融合混音工作流:用 ffmpeg 两段式 loudnorm 把多组素材 LUFS 偏差压到 <0.10,再最小干预融合、导出可进引擎的独立分轨。 标签/关键词:音频混音 响度匹配 LUFS ffmpeg 游戏音频 音效设计 Wwise FMOD 分轨导出 后期处理 触发词:混音 · 响度匹配 · LUFS 对齐 · MIX 版本 · 音乐音效分轨 · 融合 · 不打架 · 不能盖住 适用场景 :游戏音频集成、影视短视频配乐、播客后期