# Developer Portal — AugeCoin

> **Build with AUGE.** Integrate payments, wallets and smart contracts into any platform.

---

## Table of Contents

1. [Quick Start](#quick-start)
2. [Authentication](#authentication)
3. [REST API Reference](#rest-api-reference)
4. [JSON-RPC Reference](#json-rpc-reference)
5. [TypeScript SDK](#typescript-sdk)
6. [Python SDK](#python-sdk)
7. [Payment Gateway](#payment-gateway)
8. [Subscription Billing](#subscription-billing)
9. [Smart Contracts (AUGE20)](#smart-contracts-auge20)
10. [Rate Limits & Pricing](#rate-limits--pricing)
11. [Webhooks](#webhooks)
12. [Examples](#examples)
13. [FAQ](#faqu)

---

## Quick Start

### 1. Register your developer account

```bash
curl -X POST https://gateway.augecoin.io/v1/developers/register \
  -H "Content-Type: application/json" \
  -d '{"name": "Acme Corp", "email": "dev@acme.com"}'

# Response:
# { "developer_id": "...", "api_key": "aug_...", "tier": "free" }
```

Save the `api_key` — it is shown **only once**.

### 2. Install the SDK

```bash
# TypeScript / Node.js
npm install @augecoin/sdk

# Python
pip install augecoin-sdk
```

### 3. Make your first call

```typescript
// TypeScript
import { RpcClient, AUGESAT_PER_AUGE } from "@augecoin/sdk";

const rpc = new RpcClient({ rpcUrl: "https://gateway.augecoin.io", apiKey: "aug_..." });

const account = await rpc.getAccount(1);
console.log("Account #1 balance:", account.balance, "augesat");
// → balance in augesat (1 AUGE = 100,000,000 augesat)
```

```python
# Python
from augecoin_sdk import AugecoinClient

client = AugecoinClient(rpc_url="https://gateway.augecoin.io", api_key="aug_...")
account = await client.get_account(1)
print(f"Balance: {account['balance']} augesat")
```

---

## Authentication

The gateway accepts two authentication methods:

### API Key (recommended)

Pass your API key in the `x-api-key` header:

```bash
curl https://gateway.augecoin.io/v1/node/status \
  -H "x-api-key: aug_..."
```

### JWT Bearer Token

```bash
curl https://gateway.augecoin.io/v1/node/status \
  -H "Authorization: Bearer eyJ..."
```

---

## REST API Reference

All endpoints are prefixed with `https://gateway.augecoin.io/v1`.

### Node & Blockchain

| Method | Path | Description |
|--------|------|-------------|
| GET | `/node/status` | Full node status (height, peers, sync) |
| GET | `/account/{id}` | Account info by AUGEID |
| GET | `/account/{id}/balance` | Balance only (augesat + AUGE) |
| GET | `/block/{height}` | Block by number |
| GET | `/transactions/pending` | Mempool operations (paginated) |
| GET | `/contracts/auge20` | List all AUGE20 tokens |

### Developer Account

| Method | Path | Description |
|--------|------|-------------|
| GET | `/developers/me` | Your developer profile |
| POST | `/developers/keys` | Create a new API key |
| DELETE | `/developers/keys/{id}` | Revoke an API key |
| GET | `/developers/usage` | Current period usage stats |
| GET | `/developers/billing` | Billing summary + past invoices |

### Webhooks

| Method | Path | Description |
|--------|------|-------------|
| POST | `/webhooks/register` | Register a webhook URL |
| GET | `/webhooks` | List your webhooks |
| DELETE | `/webhooks/{id}` | Delete a webhook |

---

## JSON-RPC Reference

Post to `https://gateway.augecoin.io/` (or `/v1/rpc`) with:

```json
{ "jsonrpc": "2.0", "id": 1, "method": "getaccount", "params": [1] }
```

### Read-only methods

| Method | Params | Description |
|--------|--------|-------------|
| `getaccount` | `[account_id]` | Get account info |
| `resolve_address` | `[auge1_address]` | Resolve address → AUGEID |
| `getblock` | `[block_number]` | Get block by number |
| `getblockbyhash` | `[block_hash]` | Find block by hash |
| `getblockcount` | `[]` | Current chain height |
| `getaccountcount` | `[]` | Total accounts |
| `getpendings` | `[page, per_page]` | Mempool operations |
| `nodestatus` | `[]` | Node status |
| `getvalidatorset` | `[]` | Active validators |
| `findaccounts` | `[query, max]` | Search accounts |
| `listaccountsforsale` | `[page, per_page]` | Marketplace listings |
| `contract_get` | `[contract_id]` | Contract metadata |
| `contract_balance` | `[address, contract_id]` | AUGE20 balance |
| `contract_token_info` | `[contract_id]` | AUGE20 token info |
| `contract_query` | `[contract_id, data_hex]` | Generic contract query |
| `contract_simulate` | `[contract_id, data_hex]` | Dry-run execution |
| `contract_estimate_gas` | `[contract_id, data_hex]` | Gas estimate |
| `contract_events` | `[contract_id]` | Contract events |
| `contract_list_auge20` | `[]` | All AUGE20 tokens |

### Write methods (user-signed)

| Method | Params | Description |
|--------|--------|-------------|
| `sendoperation` | `[op_hex]` | Submit signed operation |
| `sendoperations` | `[op_hex_array]` | Batch submit (max 100) |
| `buyaccount` | `[op_hex, sig_hex]` | Buy an AUGEID |
| `sellaccount` | `[op_hex, sig_hex]` | List AUGEID for sale |
| `giftaccount` | `[op_hex, sig_hex]` | Gift an AUGEID |
| `acceptgift` | `[op_hex, sig_hex]` | Accept gift |
| `cancelsale` | `[op_hex, sig_hex]` | Cancel listing |

---

## TypeScript SDK

### Installation

```bash
npm install @augecoin/sdk
```

### Full example — check balance

```typescript
import { RpcClient, HdWallet, PaymentGateway, SubscriptionBilling } from "@augecoin/sdk";

// 1. Connect
const rpc = new RpcClient({ rpcUrl: "https://rpc.testnet.augecoin.io" });

// 2. Query chain
const status = await rpc.getNodeStatus();
console.log("Block height:", status.block_height);

const account = await rpc.getAccount(1);
console.log("Account #1 balance:", Number(account.balance) / 1e8, "AUGE");

// 3. Create a wallet
const wallet = await HdWallet.generate();
console.log("Mnemonic:", wallet.mnemonic); // store securely!
const keypair = await wallet.derive(0);
console.log("Address:", keypair.address);

// 4. Accept payments
const gw = new PaymentGateway({
  rpcUrl: "https://rpc.testnet.augecoin.io",
  merchantAccount: 1,
  confirmations: 1,
});

const session = await gw.createSession({
  amountAuge: 0.05,
  memo: "Order #42",
  metadata: { orderId: "42" },
});

gw.on((event) => {
  console.log(`Event: ${event.type} for session ${event.session.id}`);
});
```

### PaymentGateway — detailed usage

```typescript
// Create payment session
const session = await gw.createSession({
  amountAuge: 0.1,
  memo: "Premium subscription",
  ttlSeconds: 900,       // 15 min default
  metadata: {
    orderId: "ORD-2024-001",
    customerEmail: "user@example.com",
  },
});

// Generate QR code URI
const qrUri = gw.paymentUri(session.payerAddress ?? "", {
  amountAuge: session.amountAuge,
  label: "Acme Store",
  memo: session.memo,
});

// Verify payment (server-side, idempotent)
const result = await gw.verifyPayment({ sessionId: session.id });
if (result.confirmed) {
  console.log("Payment confirmed! Hash:", result.session.transactionHash);
}

// Listen for events
const unsub = gw.on((event) => {
  if (event.type === "payment.confirmed") {
    // fulfill order
    await sendConfirmationEmail(event.session.metadata?.orderId);
    unsub();
    gw.destroy();
  }
});
```

### SubscriptionBilling

```typescript
const billing = new SubscriptionBilling({
  plans: [
    { id: "basic",  name: "Basic",   amountAuge: 0.10, interval: "month", intervalCount: 1 },
    { id: "pro",    name: "Pro",     amountAuge: 0.50, interval: "month", intervalCount: 1 },
    { id: "yearly", name: "Yearly",  amountAuge: 5.0,  interval: "year",  intervalCount: 1 },
  ],
  rpc,
  sign: async (hex) => { /* sign payload with merchant key */ return signature; },
  publicKeyHex: merchantPublicKey,
  account: 1,
  chainId: 2,
});

billing.startBilling();

// Start a subscription
const sub = await billing.start({
  planId: "pro",
  trialDays: 14,
  metadata: { customerId: "cust_123" },
});

// Listen for billing events
billing.on((event) => {
  console.log(`[${event.type}] subscription=${event.subscription.id}`, event.error ?? "");
});
```

### Send a transfer

```typescript
import { serializeTransaction, signedOpToString } from "@augecoin/sdk";

// 1. Fetch the account to get current n_operation
const acct = await rpc.getAccount(senderAugeId);
const nOp = acct.n_operation;

// 2. Build + sign the operation
const signedOp = serializeTransaction(
  {
    senderAccount: senderAugeId,
    receiver: receiverAugeId,
    amountAugesat: BigInt(Math.round(0.05 * 1e8)),
    nOperation: nOp,
  },
  publicKeyHex,
  signatureHex,  // from HdWallet.derive().sign(payload)
);

// 3. Submit
const result = await rpc.sendOperation(signedOpToString(signedOp));
console.log("Tx hash:", result.hash);
```

---

## Python SDK

### Installation

```bash
pip install augecoin-sdk
```

### Example

```python
import asyncio
from augecoin_sdk import (
    AugecoinClient, AugecoinClientConfig,
    KeyPair, HdWallet, Chain,
    auge_to_augesat, format_auge,
)

async def main():
    # Connect
    client = AugecoinClient(
        AugecoinClientConfig(rpc_url="https://rpc.testnet.augecoin.io")
    )

    # Check balance
    account = await client.get_account(1)
    raw = int(account["balance"])
    print(f"Account #1: {format_auge(raw)} AUGE")

    # Create wallet
    wallet = HdWallet()
    kp = wallet.derive(0)
    print(f"Address: {kp.address('testnet')}")

    # Get node status
    status = await client.get_node_status()
    print(f"Block height: {status['block_height']}")

asyncio.run(main())
```

---

## Payment Gateway

### For merchants

The `PaymentGateway` class in both SDKs handles the full payment lifecycle:

1. **CreateSession** — generates a time-limited, unique payment address
2. **Monitor** — polls the mempool + chain for the matching transfer
3. **Confirm** — waits for N block confirmations
4. **Webhook** — fires a signed POST to your server
5. **Verify** — idempotent; safe to call multiple times

### Security notes

- Payment sessions expire after 15 minutes (configurable)
- Webhook payloads are HMAC-signed; verify `x-augecoin-signature`
- Never trust the client-side amount — always verify on-chain
- Use `verifyTransaction()` server-side for manual payment verification

---

## Subscription Billing

The SDK includes a complete subscription billing engine:

- **Plan management** — create hourly/daily/weekly/monthly/yearly plans
- **Automatic billing** — background poll every 10 seconds
- **Grace period** — configurable days before marking as `past_due`
- **Retry logic** — configurable max attempts before cancellation
- **Events** — `charged`, `failed`, `cancelled`, `trial_will_end`

---

## Smart Contracts (AUGE20)

```typescript
import { ContractClient, TokenClient, encodeTokenInit } from "@augecoin/sdk";

// Deploy a new AUGE20 token (admin only)
const tokenInit = encodeTokenInit({
  name: "My Token",
  symbol: "MTK",
  decimals: 8,
  initialSupply: BigInt(1_000_000_000_00000000n), // 1M tokens
  maxSupply:    BigInt(10_000_000_000000000n),
  mintEnabled: true,
  burnEnabled: true,
});

// Simulate before deploying
const sim = await rpc.contractSimulate(contractId, callData);
if (!sim.ok) throw new Error(`Simulation failed: ${sim.error}`);

// Execute
const result = await rpc.contractExecute(opHex);
```

---

## Rate Limits & Pricing

| Tier | RPM | Monthly Quota | Monthly Fee | Overage per call |
|------|-----|---------------|-------------|-----------------|
| Free | 10 | 1,000 calls | 0 AUGE | 500 augesat |
| Pro | 60 | 100,000 calls | 10 AUGE | 200 augesat |
| Business | 300 | 1,000,000 calls | 50 AUGE | 50 augesat |
| Enterprise | 3,000 | Unlimited | Negotiated | — |

- All tiers include access to `/health`, `/readyz`, `/v1/pricing`
- Mainnet access requires Pro tier or higher
- Admin methods (contract deploy, validator management) require Business tier
- Overage is billed per-call in real-time

### Upgrade tier

```bash
# Contact: billing@augecoin.io
# Or via the developer portal (coming soon)
```

---

## Webhooks

### Register a webhook

```bash
curl -X POST https://gateway.augecoin.io/v1/webhooks/register \
  -H "x-api-key: aug_..." \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://your-server.com/webhooks/augecoin",
    "events": ["payment.confirmed", "payment.expired"],
    "secret": "your-hmac-secret"
  }'
```

### Supported events

| Event | When fired |
|-------|-----------|
| `payment.confirmed` | Payment confirmed after required confirmations |
| `payment.expired` | Payment session expired unpaid |
| `payment.failed` | Payment verification failed |
| `subscription.charged` | Recurring billing charge succeeded |
| `subscription.failed` | Recurring billing charge failed |
| `subscription.cancelled` | Subscription cancelled |

### Verify webhook signature

```typescript
import crypto from "crypto";

function verifyWebhookSignature(body: string, signature: string, secret: string): boolean {
  const expected = "sha256=" + crypto.createHmac("sha256", secret).update(body).digest("hex");
  return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected));
}
```

---

## Examples

See the `examples/` directory:

| Example | Path | Description |
|---------|------|-------------|
| Site integration | `examples/site-integration/` | HTML page with checkout flow |
| Payment gateway | `examples/payment-gateway/` | Express + FastAPI backends |
| POS terminal | `examples/pos-terminal/` | Point-of-sale with QR codes |
| Subscription billing | `examples/subscription-billing/` | Recurring billing API |

### Run examples

```bash
# Payment gateway (Node.js)
cd examples/payment-gateway
npm install && npx tsx server.ts

# Payment gateway (Python)
cd examples/payment-gateway
uvicorn server:app --port 3000

# POS terminal
cd examples/pos-terminal
pip install qrcode fastapi uvicorn
uvicorn pos:app --port 8001

# Subscription billing
cd examples/subscription-billing
uvicorn server:app --port 8002
```

---

## FAQ

**Q: What is an augesat?**
A: The smallest unit of AUGE. 1 AUGE = 100,000,000 (10⁸) augesat, like satoshis for Bitcoin.

**Q: How do I get testnet AUGE?**
A: Use the faucet RPC endpoint or request from the AugeCoin community testnet faucet.

**Q: Where do I store my API key?**
A: In environment variables. Never commit it to version control. Use a secrets manager in production.

**Q: How long does block confirmation take?**
A: ~5 seconds per block on average. 1 confirmation ≈ 5 seconds.

**Q: Can I accept AUGE payments without running my own node?**
A: Yes — use the REST Gateway (`gateway.augecoin.io`). No node required.

**Q: What chains are supported?**
A: Mainnet (chain_id=1), Testnet (chain_id=2), Devnet (chain_id=3).

**Q: How do I report a bug?**
A: Open an issue at https://github.com/augecoin/augecoin or email dev@augecoin.io.
