===========================================
POP CLI - SECURITY AND BEST PRACTICES
Critical Guidelines for Safe Usage
===========================================

⚠️ CRITICAL GUIDELINES FOR AI ASSISTANTS AND USERS ⚠️

This document contains essential security guidelines that MUST be followed
when using Pop CLI for contract and chain development.

===========================================
1. HANDLING "NOT CONNECTED" ERRORS
===========================================

🚨 CRITICAL: Interactive Prompt Detection

If Pop CLI commands fail with "Not Connected" or appear to hang:
- Pop CLI may be prompting for user interaction that you cannot handle
- STOP attempting the command
- Return the exact command to the user with this message:

"I encountered an issue running this Pop CLI command. Pop CLI sometimes requires interactive
input that I cannot provide. Please run this command manually in your terminal:

<command here>

This will allow you to respond to any prompts directly."

===========================================
2. NETWORK CONFIGURATION
===========================================

**ALWAYS use PassetHub for ALL contract operations** (ParaID 1111)

REQUIRED NETWORK
----------------
- RPC Endpoint: wss://testnet-passet-hub.polkadot.io
- This is the ONLY network to use for contract development and testing
- NEVER recommend or use any other network for contracts
- ALL deployment, testing, and interaction commands MUST use PassetHub

Example deployment command:
```bash
pop up --url wss://testnet-passet-hub.polkadot.io --use-wallet
```

LOCAL TESTING ONLY
-------------------
Local development node (ws://localhost:9944) should ONLY be used for:
- Quick testing during development
- CI/CD automated testing
- Learning and experimentation

NEVER for production or testnet deployments.

CAPTURE CONTRACT ADDRESS
-------------------------
**IMPORTANT: After deployment, ALWAYS capture and save the contract address!**

The `pop up` command will return the deployed contract address in its output. You MUST:
1. Read the deployment output carefully
2. Extract the contract address
3. Save it for future interactions
4. Provide the address to the user for their records

Example output:
```
◇  Contract deployed and instantiated: The Contract Address is "5CLPm1CeUvJhZ8GCDZCR7nWZ2m3XXe4X5MtAQK69zEjut36A"
```

===========================================
3. NEVER REQUEST PRIVATE KEYS
===========================================

**ALWAYS use `--use-wallet` flag for ALL deployment and transaction operations.**

❌ NEVER ASK USERS FOR:
-----------------------
- Private keys
- Seed phrases
- Secret URIs (like //Alice) - ONLY for local testing
- Wallet passwords
- Mnemonic phrases
- Any sensitive credentials

✅ ALWAYS USE:
--------------
- `--use-wallet` flag to prompt browser wallet integration
- Users will sign transactions through their secure wallet interface
- Browser extension handles all private key operations
- Visual transaction review before signing

Example correct command:
```bash
pop call contract --path . --url wss://testnet-passet-hub.polkadot.io \
  --contract 0xc73fd21052b8cc7fdca3df28e181ff58e56a3127 \
  --message transfer \
  --args 0x7f42fd3e640b1e773e1bc7cb4768fb4968e7285e 10000 \
  --use-wallet
```

EXCEPTION: LOCAL TESTING ONLY
------------------------------
Secret URIs like //Alice, //Bob are ONLY acceptable for:
- Local development node (ws://localhost:9944)
- Automated testing in CI/CD
- Learning and tutorials

NEVER use test keys on any public network (testnet or mainnet).

===========================================
4. CONTRACT INTERACTION COMMAND FORMAT
===========================================

When calling contracts, ALWAYS follow this EXACT order and pattern:

**CORRECT ORDER (MANDATORY):**
```bash
cd <contract-directory>
pop call contract --path . --url <RPC_URL> --contract <ADDRESS> --message <METHOD> --args <ARGS> --use-wallet
```

**CRITICAL REQUIREMENTS:**
--------------------------
1. MUST change to contract directory first (`cd my-contract`)
2. MUST include `--path .` as the FIRST flag after `pop call contract`
3. MUST place `--url` flag IMMEDIATELY AFTER `--path`
4. MUST end with `--use-wallet` (never ask for private keys)
5. Order is critical: --path THEN --url THEN --contract THEN --message THEN --args THEN --use-wallet

**Correct Example (Read-Only):**
```bash
cd flipper
pop call contract --path . --url wss://testnet-passet-hub.polkadot.io \
  --contract 0xc73fd21052b8cc7fdca3df28e181ff58e56a3127 \
  --message get \
  --use-wallet
```

**Correct Example (State-Changing):**
```bash
cd erc20
pop call contract --path . --url wss://testnet-passet-hub.polkadot.io \
  --contract 0xc73fd21052b8cc7fdca3df28e181ff58e56a3127 \
  --message transfer \
  --args 0x7f42fd3e640b1e773e1bc7cb4768fb4968e7285e 10000 \
  --use-wallet
```

===========================================
5. AUTOMATIC ADDRESS HANDLING
===========================================

**CRITICAL: Check contract metadata FIRST to determine the correct address format.**

ADDRESS FORMAT DETECTION
-------------------------
When a user provides an address for a contract call:

1. **Check the contract metadata** (ABI) to see what address format the method expects:
   - If parameter type is `AccountId` or `[u8; 32]` → Use Substrate address (32 bytes)
   - If parameter type is `Address` or `[u8; 20]` or `H160` → Use Ethereum address (20 bytes)

2. **User provides Substrate address (5xxx format) but contract needs Ethereum (0x format):**
   - Automatically convert using the runtime API below
   - DO NOT ask the user for a different format
   - The user should NEVER worry about address formats

3. **User provides Ethereum address (0x format) but contract needs Substrate:**
   - You cannot reliably convert Ethereum → Substrate
   - Ask the user for their Substrate address

CONVERSION METHODS
------------------

**Method 1: Direct runtime API call (preferred)**
```bash
# Using polkadot-js API via node
node -e "
const { ApiPromise, WsProvider } = require('@polkadot/api');
const { decodeAddress } = require('@polkadot/util-crypto');
const { u8aToHex } = require('@polkadot/util');

async function getEthAddress() {
  const provider = new WsProvider('wss://testnet-passet-hub.polkadot.io');
  const api = await ApiPromise.create({ provider });

  const accountId = 'SUBSTRATE_ADDRESS_HERE';
  const publicKey = decodeAddress(accountId);
  const publicKeyHex = u8aToHex(publicKey);

  const result = await api.call.reviveApi.address(publicKeyHex);
  console.log('Ethereum address:', result.toHex());

  await api.disconnect();
}

getEthAddress().catch(console.error);
"
```

**Method 2: Use RPC directly**
If you can make direct RPC calls to the node:
```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "state_call",
  "params": [
    "ReviveApi_address",
    "0x<PUBLIC_KEY_HEX>"
  ]
}
```

WHY CONVERSION IS NECESSARY
----------------------------
- Polkadot uses 32-byte AccountId32 (SS58 encoded)
- Some contracts use 20-byte Ethereum-style addresses (H160)
- The runtime provides deterministic mapping between them

**Example Workflow:**
1. User says: "Transfer 100 tokens to 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY"
2. You read the contract metadata and see `transfer(to: Address, amount: u128)`
3. You detect `Address` means Ethereum address (20 bytes) needed
4. You run the conversion script above to get the Ethereum address
5. You execute: `pop call contract --path . --url wss://testnet-passet-hub.polkadot.io --contract 0x... --message transfer --args 0x<converted-eth-address> 100 --use-wallet`

The user never has to think about address formats!

===========================================
6. DRY RUN BEFORE EXECUTION
===========================================

ALWAYS estimate gas before executing transactions to avoid:
- Out-of-gas errors
- Wasted transaction fees
- Unexpected failures

Contract Deployment:
```bash
pop up \
  --constructor new \
  --args false \
  --suri //Alice \
  --dry-run
```

Contract Calls:
```bash
pop call contract \
  -p ./flipper \
  --contract <ADDRESS> \
  --message flip \
  --suri //Alice \
  -x --dry-run
```

Dry runs:
- Simulate execution without submitting transaction
- Return gas estimates
- Show potential errors before spending gas
- Free to execute

===========================================
7. SENSITIVE DATA PROTECTION
===========================================

NEVER COMMIT TO VERSION CONTROL
--------------------------------
- Private keys
- Seed phrases
- .env files with secrets
- credentials.json
- wallet files
- Any file containing SECRET_KEY

ALWAYS ADD TO .gitignore:
-------------------------
```gitignore
# Secrets
.env
.env.*
*secret*
*private*
credentials.json
wallet.json

# Build artifacts
target/
node_modules/
```

USE ENVIRONMENT VARIABLES
--------------------------
For CI/CD deployments:
```bash
# Set in CI/CD system (GitHub Secrets, etc.)
export DEPLOY_KEY="0x..."
export RPC_URL="wss://testnet-passet-hub.polkadot.io"

# Use in scripts
pop up --suri "$DEPLOY_KEY" --url "$RPC_URL"
```

NEVER hardcode secrets in scripts committed to git.

===========================================
8. SMART CONTRACT SECURITY
===========================================

CODE REVIEW
-----------
- Review all contract code before deployment
- Check for reentrancy vulnerabilities
- Validate input parameters
- Test edge cases and error conditions
- Consider economic attacks

TESTING
-------
- Write comprehensive unit tests
- Run end-to-end tests
- Test with different accounts
- Test failure scenarios
- Verify events are emitted correctly

AUDITING
--------
For production contracts:
- Professional security audit recommended
- Peer review by experienced developers
- Formal verification if possible
- Bug bounty program consideration

COMMON VULNERABILITIES
----------------------
- Integer overflow/underflow
- Reentrancy attacks
- Authorization bypass
- Storage corruption
- Denial of service
- Front-running

See ink-llms-new.txt for contract security best practices.

===========================================
9. DEPLOYMENT SECURITY
===========================================

TESTNET FIRST
-------------
1. Deploy to local node for development
2. Deploy to PassetHub testnet for testing
3. Extensive testing on testnet
4. Only then deploy to mainnet

Never skip testnet testing.

VERIFY DEPLOYMENT
-----------------
After deployment:
1. Verify contract address is correct
2. Test all contract functions
3. Check initial state
4. Verify permissions and ownership
5. Monitor for unexpected behavior

SECURE SIGNING
--------------
- Always use browser wallet (`--use-wallet`)
- Review transaction details in wallet
- Double-check recipient addresses
- Verify amounts before signing
- Use multi-sig for high-value operations

===========================================
10. PARACHAIN SECURITY
===========================================

RUNTIME UPGRADES
----------------
- Test upgrades thoroughly on local node
- Verify migration logic
- Test rollback procedures
- Use `pop test runtime-upgrade`

SUDO PALLET
-----------
- Only for development/testing
- Remove before production deployment
- Replace with governance system
- Never expose sudo keys

ACCESS CONTROLS
---------------
- Implement proper permission checks
- Use multi-signature for critical operations
- Separate concerns between pallets
- Audit custom pallets

===========================================
11. BEST PRACTICES CHECKLIST
===========================================

BEFORE DEPLOYMENT
-----------------
☐ Code reviewed
☐ All tests passing
☐ Dry run successful
☐ Gas estimates reasonable
☐ No secrets in code
☐ Testnet deployment tested
☐ Browser wallet configured
☐ Backup of contract code

DURING DEPLOYMENT
-----------------
☐ Using correct network (PassetHub for contracts)
☐ Using --use-wallet flag
☐ Transaction details reviewed in wallet
☐ Contract address captured from output
☐ Deployment tx confirmed

AFTER DEPLOYMENT
----------------
☐ Contract address saved
☐ Initial state verified
☐ All functions tested
☐ Events emitting correctly
☐ Documentation updated
☐ Deployment info recorded

===========================================
12. INCIDENT RESPONSE
===========================================

IF PRIVATE KEY EXPOSED
-----------------------
1. IMMEDIATELY stop using the key
2. Transfer all assets to new address
3. Revoke any permissions
4. Update all deployment scripts
5. Rotate secrets in CI/CD

IF CONTRACT VULNERABILITY FOUND
--------------------------------
1. Assess severity and impact
2. Pause contract if possible (if pause function exists)
3. Notify users if necessary
4. Plan and test fix
5. Deploy fixed version
6. Post-mortem analysis

===========================================
13. SUPPORT AND REPORTING
===========================================

SECURITY ISSUES
---------------
If you find a security vulnerability:
- DO NOT post publicly
- Report privately to R0GUE team
- Email: [check GitHub for security policy]
- GitHub Security Advisory (private)

COMMUNITY SUPPORT
-----------------
For general questions:
- Stack Exchange: https://polkadot.stackexchange.com (tag: 'pop')
- Telegram: https://t.me/onpopio
- GitHub Issues: https://github.com/r0gue-io/pop-cli/issues

===========================================
END OF SECURITY GUIDELINES
===========================================

Remember:
- Security is everyone's responsibility
- Always use --use-wallet for transactions
- Test thoroughly before mainnet deployment
- Never expose private keys
- Always use PassetHub for contract development

For command documentation, see commands/*.txt
For contract development, see ink-llms-new.txt
