# PUGONG：从读取到成交

这是蒲公英公开操作说明。唯一销售合约 `0xc39359E096575269989598e3134Ea5c77D9662Ee`；BNB Smart Chain 56；开卖时间 2026-11-21 22:59:48（UTC+8，`opensAt()` = 1795273188）。参数以实际 getter 为准。文件描述接口，不代替钱包主人的付款授权。

## 读到的地址，须与读到的代码一致

从 `config.js` 取得唯一销售地址，与 `agent.json` 交叉核对。检查 `https://bscscan.com/address/0xc39359E096575269989598e3134Ea5c77D9662Ee#code` 的源码、链上 bytecode 与编译 ABI。

销售合约和代币的 `owner()` 均为零地址，无管理员、暂停或升级入口；份额上限和代币供给上限固定。没有可任意改收款目标的入口。用源码及 getter 验证这些事实。

登记合约 `AGENT_REGISTRY()` 应为 `0x60B9262456dE011F7d15a54CdD8c48bAaa8B022F`，路由 `PANCAKE_ROUTER()` 应为 `0x10ED43C718714eb63d5aA57B78B54704E256024E`。读出 `token()`、`pair()`、`recipient()`，核对代币的 `ROUND()`、`LP_PAIR()`、`DEX_ROUTER()`；不要将销售地址当成代币地址。

## 额度是一条可计算的生长线

部署目标：每份 0.005 BNB、100,000 PUGONG，总量 10,000 份。每个有效 Agent ID 基本可买 15 份。绑定你为推荐人的钱包每买 1 份，你的 ID 多 1 份可购额度，最多 150 份。只算直推，绑定前的购买不补算；推荐人的 ID 须仍有效且不同于买家的 ID，才增加额度。解锁量不送代币，仍要照价购买，不能转让；销售卖完或到期即停止使用。

`canBuy(address)` 只看 ID 剩余额度，`capOf(address)` 是上限，实际可买还受销售剩余量和时间限制。更换持有 ID 不会重置已用额度；已购钱包绑定了原 ID 时，不能换 ID 继续买。

先读 `agentIdentity(buyer)`。若使用推荐，单独确认并调用 `bindReferrer(referrer)`：推荐人须有有效 Agent ID，不可为自己或零地址；绑定不可更改，开卖前就可做。未绑定时的 preview 不会计入新推荐人的效果。在买入入口附无效推荐地址会被忽略，因此建议先单独绑定，再重新报价。

合格推荐带来实际成交额的 5% BNB 推荐金，买家多拿 5% PUGONG。被推荐 ID 累计首次从不足 15 跨到至少 15 份的那笔成交，双方各另得 0.00125 BNB，每个被推荐 ID 一次，总预算 1 BNB 发完为止。它是累计门槛，可以分几次买；先已买到 15 份再绑定不补发。双方分别在同笔交易支付，失败的一方记入 `rewardsOwed(address)`，由同一地址调用 `claimRewards()` 领取；领取钱包此时须能接收 BNB。

数字例：直推在绑定后买 15 份，成交额 0.075 BNB；此前未解锁的推荐人上限由 15 到 30 份，获得 0.00375 BNB 推荐金，买家获得 1,500,000 基础 PUGONG 与 75,000 加成 PUGONG。若该笔首次跨过门槛且预算充足，双方各另得 0.00125 BNB。预算读 `unlockRules()` 第 8 个返回值。任何新交易都须重读实际预览，不能由此例假定奖励仍有剩余。

## 一次报价的全部返回值

`previewBuy(buyer,qty)` → `shares,cost,tokens,available,ok,bonusTokens,unlocks,welcomeToRef,welcomeBack`。总实得代币＝tokens＋bonusTokens；cost 与奖励都是 wei。

`previewPayment(buyer,valueWei)` → `qty,cost,change,ok`。整数 wei，禁止浮点换算。`snapshot()` → `live,poolAdded,sold,total,price,opens,closes,raisedWei`。`opensAt()` 与 `closesAt()` 是链上时间来源。

付款决定份数：`min(value/sharePrice 向下取整, canBuy, 销售剩余)`。所有六种付款入口都如此，数量参数只供报价。未成交的余额同笔退回。付款不足一份会 `PayAtLeast(price,sent)` 回退；没有额度、没有 ID、尚未开卖、到期或已经开池同样不能成交。付款最终，不退本金。多付时必须能收 BNB；拒收 BNB 的合约钱包应付准确成本。奖励付款失败的记账机制不会替代找零，找零被拒收会回退整个购买。

单价 0.005 BNB，报价 2 份，额度与剩余都足够时：

| 支付 | 实得份数 | 退回 BNB |
|---|---:|---:|
| 0.010000000000000001 BNB | 2 | 0.000000000000000001 |
| 0.02 BNB | 4 | 0 |
| 0.009999999999999999 BNB | 1 | 0.004999999999999999 |
| 0.004999999999999999 BNB | 交易回退 | 无成交 |

可通过 `mint()`、`mint(uint256)`、`mint(uint256,address)`、`mintMany(uint256)`、`mintWithReferrer(uint256,address)`、直接转 BNB 成交。带推荐人的入口只在尚未绑定时尝试绑定，不会更改已有推荐。

## 完整 ethers 6 读数与模拟示例

浏览器页面已经内置固定版本 ethers。Node 调用可使用 ethers 6；示例只准备与模拟，不签名、不广播。将 RPC_URL、BUYER、CONTRACT 换成明确核对的值。不能将占位符当作可执行地址。

```javascript
import { JsonRpcProvider, Contract, Interface, ZeroAddress } from 'ethers';
import fs from 'node:fs';
const p = new JsonRpcProvider(process.env.RPC_URL, 56,
  { batchMaxCount: 1, cacheTimeout: -1 });
const CA = '0xc39359E096575269989598e3134Ea5c77D9662Ee', buyer = process.env.BUYER;
const abi = JSON.parse(fs.readFileSync('abi.json', 'utf8'));
const sale = new Contract(CA, abi, p);
if (Number((await p.getNetwork()).chainId) !== 56) throw Error('chain');
if (await p.getCode(CA) === '0x') throw Error('no code');
if (await sale.owner() !== ZeroAddress) throw Error('owner');
if (!(await sale.agentIdentity(buyer))[1]) throw Error('Agent ID required');
// If binding a referrer, simulate and separately confirm bindReferrer first;
// wait for its successful receipt, then start the quote below again.
const requested = 2n;
const before = await sale.previewBuy(buyer, requested);
const value = before.cost;
const payment = await sale.previewPayment(buyer, value);
const assets = await sale.previewBuy(buyer, payment.qty);
if (!payment.ok || !assets.ok) throw Error('not buyable');
const tx = { from: buyer, to: CA,
  data: new Interface(abi).encodeFunctionData('mint(uint256)', [payment.qty]),
  value };
await p.call(tx);
const estimated = await p.estimateGas(tx);
const padded = (estimated * 125n + 99n) / 100n;
const gasLimit = padded > 700000n ? padded : 700000n;
console.log({ shares: payment.qty.toString(), value: value.toString(),
  change: payment.change.toString(),
  tokens: (assets.tokens + assets.bonusTokens).toString(),
  referrerUnlocks: assets.unlocks.toString(),
  welcomeToReferrer: assets.welcomeToRef.toString(),
  welcomeToBuyer: assets.welcomeBack.toString(), gasLimit: gasLimit.toString() });
// Present these exact values for owner approval. Before signing, re-read and
// compare the payment and all asset/reward fields, account and chain.
// A change requires a new preview and approval. Unknown receipts block resends.
await p.destroy();
```

`tools` 中的本地验证文件不属于公开交易流程。无需私钥、助记词或无限授权即可读取与模拟。

## 开池与领取

最后一份成交自动开池。到期后且有成交时，任何人可调用 `finalize()`，先查 `canFinalize()` 并模拟、估算。零成交不开池。LP 送 `0x000000000000000000000000000000000000dEaD`。池内 BNB 不少于已售总额的 75%；开盘价不低于铸造价。开池前 `openingPrice()` 是按当前销售与 pair 中 WBNB 算的预览，不是未来固定倍数；开池后是历史开盘值。

有推荐时，实际成交额的 75% 用于池、5% 推荐金、20% 收款地址；无推荐时为 75% 池、25% 收款地址。双边达标奖励从收款部分出，不动池子。读 `allocation()` 核实。

待领款：读 `rewardsOwed(buyer)`；大于零且钱包能接收 BNB 时，用同一地址模拟并确认 `claimRewards()`，value=0。不要替别人调用，也不要仅因支付当笔没有转账就判定奖励丢失。

## 开池后的卖出路径

代币在开池前不开放转账。开池后，官方交易对买入／卖出的部署目标均为 2%，钱包间转账无此税；读代币的 `BUY_FEE_BPS()`、`SELL_FEE_BPS()`。使用真实路由的 `swapExactTokensForETHSupportingFeeOnTransferTokens` 卖出。BNB 买入用 `swapExactETHForTokensSupportingFeeOnTransferTokens`。

```javascript
// Continue with a provider, sale and buyer you have verified above.
const token = new Contract(await sale.token(), [
  'function trading() view returns(bool)',
  'function DEX_ROUTER() view returns(address)',
  'function WRAPPED_BNB() view returns(address)',
  'function balanceOf(address) view returns(uint256)',
  'function allowance(address,address) view returns(uint256)',
  'function approve(address,uint256) returns(bool)',
  'function SELL_FEE_BPS() view returns(uint256)'
], p);
if (!await token.trading()) throw Error('pool not open');
const routerAddress = await token.DEX_ROUTER();
if (routerAddress.toLowerCase() !== (await sale.PANCAKE_ROUTER()).toLowerCase())
  throw Error('router mismatch');
const tokenAddress = await sale.token(), wrapped = await token.WRAPPED_BNB();
const amount = await token.balanceOf(buyer); // replace with owner-approved amount
if (amount === 0n) throw Error('no tokens');
const fee = await token.SELL_FEE_BPS();
const netInput = amount - amount * fee / 10000n;
const router = new Contract(routerAddress, [
  'function getAmountsOut(uint256,address[]) view returns(uint256[])',
  'function swapExactTokensForETHSupportingFeeOnTransferTokens(uint256,uint256,address[],address,uint256)'
], p);
const path = [tokenAddress, wrapped];
const estimateOut = (await router.getAmountsOut(netInput, path))[1];
const minOut = estimateOut * 97n / 100n; // example 3%; owner chooses tolerance
if (minOut === 0n) throw Error('no usable minimum');
const approval = { from: buyer, to: tokenAddress,
  data: token.interface.encodeFunctionData('approve', [routerAddress, amount]) };
await p.call(approval); await p.estimateGas(approval);
// Only after owner approval: submit EXACT amount approval and await receipt.
// Then re-read balance, tax, allowance, reserves and minOut, simulate the sell.
const deadline = BigInt((await p.getBlock('latest')).timestamp) + 300n;
const sell = { from: buyer, to: routerAddress,
  data: router.interface.encodeFunctionData(
    'swapExactTokensForETHSupportingFeeOnTransferTokens',
    [amount, minOut, path, buyer, deadline]) };
// This simulation succeeds only after sufficient exact approval is confirmed.
await p.call(sell); const sellGas = await p.estimateGas(sell);
// Present amount, minOut and gas for owner confirmation; do not auto-submit.
```

第一段示例已关闭 provider；卖出段是另一段独立操作，须先重新创建同样核对过的 provider、sale 和 buyer。`getAmountsOut` 的税后输入估算只是当前值；用带真实 from 的完整卖出模拟确认，最低收到金额须由用户选择，不能默认为零。

## English operating notes

Read the unique address, verified source, bytecode, registry, router, token and pair before preparing a transaction. Base allowance is 15 shares per valid Agent ID; every direct referred share unlocks 1 extra paid allowance up to 150. Only post-link purchases count, with distinct valid IDs. A referrer is permanent and can be linked before opening. A linked purchase pays 5% of actual cost to the referrer and adds 5% tokens to the buyer. When a referred ID first crosses 15 cumulative shares, each side gets 0.00125 BNB, once per ID, while the 1 BNB total budget remains. Failed reward transfers become claims by the same address.

Use previewPayment for exact wei and previewBuy for all tokens and effects. Payment decides shares; quantity is quote-only. Unused BNB is returned in the same transaction. A wallet rejecting change causes the purchase to revert; send exact cost in that case. Less than one share, no allowance, missing ID, closed or not-yet-open sale cannot buy. Payments are final, without principal refunds. Simulate from the real buyer and use max(700000, ceil(estimateGas×1.25)), including the final purchase that seeds liquidity. Re-read immediately before signing; changes require another confirmation. Pending or unknown receipts must not be resubmitted.

The pool opens automatically on sellout or through finalize() after expiry with nonzero sales. At least 75% of sold value is represented by BNB in the pool, the opening price is no lower than mint, LP goes to 0xdEaD. The pre-opening preview multiple is not a promised final value. Sell only after trading() is true, using the SupportingFeeOnTransferTokens function, exact token allowance, a nonzero owner-selected minimum output, and a short deadline. The examples prepare and simulate; they never grant authority or sign.
