Nodejs SDK
Full capabilities in browsers and Node.js; HTTP by default, WSS optional.
One SDK, two runtime environments#
During initialization the creator can save initial settings, but recruitment, wars and issuance stay closed. Completing initialization permanently removes the creator’s parameter-editing rights while preserving creator and LP principal-beneficiary identity. Afterwards, settings, recipients, issuance, buybacks and extension permissions require an operations proposal and reviewer approval.
Operations edits current values and submits a proposal without changing active settings. The reviewer checks targets, amounts and changes under Parameters and review, then approves the exact stored batch. Execution is atomic and failure rolls back the batch. Proposals expire after 7 days; each approval invalidates other proposals for the old configuration revision. Game approval requires no further platform multisig or additional timelock.
Fresh deployments from 2026-10-24: Recruit 100 (default admission mining power, configurable per game) → Warrior 300 → Chief 2,700 → Retirement 8,100 mining power, paid on each actual milestone, totaling 11,200 per full cycle at the default. Later paid cycles earn real promotions again. Free seed warriors receive no admission or initial warrior reward. Taking over a seat (paid takeover or accepted transfer) pays the admission and warrior amounts on that seat's first handover (after an accepted transfer, once the new holder fills the seat); later paid takeovers pay only admission and later transfers pay nothing. Replacement is not retirement.
All mining power uses this game’s 6-decimal Honor.goldBalance ledger. Admission, promotion, retirement and the once-only profile reward increase lifetime combat power. Tasks, wars, sales and ordinary extensions only credit mining power. Spending never reduces power. Country creation/joining cost 10,000 / 20 mining power. Initial prestige imports lifetime power; leaving removes it and rejoining imports it once again.
Each game has its own mining power redemption pool. Availability, claim times and actual redemption results are determined by the game page and on-chain transactions.
Game tokens default to 6 decimals. The creator may select an integer from 0–18, including 0; decimals cannot change after issuance. One token equals 10^decimals base units: at 6 decimals, 1 token = 1,000,000 base units. Calculations use exact base units and the UI formats actual precision. mining power uses 6 decimals and BNB keeps 18 decimals; rates use bps and lifetime combat power uses integers.
TokenConfig appends a uint8 decimals field. supply, issuance budgets, transfers, approvals, tax amounts, locks, airdrops and token swap amounts remain integer base units: TypeScript bigint, Go *big.Int, and decimal integer strings in HTTP JSON. The SDK does not scale amounts automatically; token literals and budget variables in examples are also base units. Before issuance, read decimals from treasury getTokenConfig(); afterwards, read the token’s decimals(). TypeScript uses parseUnits(text, decimals) / formatUnits(raw, decimals); Go scales with integer arithmetic using 10^decimals. Avoid floating-point conversion and double scaling.
There is one JavaScript SDK: @x404/sdk, implemented in TypeScript, compiled to JavaScript, and shipped with type declarations. Node.js and browsers use the same package; JavaScript projects do not need TypeScript. ESM and CommonJS are two module formats of this package.
Node.js is a runtime; browsers run the compiled JavaScript SDK. Both the JavaScript/TypeScript and Go SDKs expose the full protocol. Choose by language and runtime; neither restricts features by frontend or backend role.
Capabilities and connections#
| Capabilities | JavaScript / TypeScript SDK | Go SDK |
|---|---|---|
| Contract queries | read / SocialClient / GameClient | Call / SocialClient / GameClient |
| Prepare and send transactions | prepare / write / wallet signer | Prepare / Transact / custom signer |
| Event decoding and historical logs | decoder / scanEvents | NewDecoder / Scan |
| Continuous HTTP synchronization | watchEvents without wakeProvider | Watch with a nil wake channel |
| Optional event subscriptions | subscribeEvents / WebSocketProvider | Subscribe / WSS ethclient |
Websites default to HTTP RPC queries and EIP-1193 wallet confirmations; chain WSS is not required. Fetch large datasets from your application API. A shared index can use either SDK and notify browsers through HTTP polling, SSE or an application WebSocket.
Browser reads and wallet interaction#
import {JsonRpcProvider, BrowserProvider} from 'ethers';
import {SocialClient} from '@x404/sdk';
const provider = new JsonRpcProvider(HTTP_RPC_URL);
const reader = new SocialClient(SOCIAL_ADDRESS, provider);
await reader.verify(CHAIN_ID);
const page = await reader.posts(0n, 20);
// Run after the user clicks Connect Wallet; obtain eip1193Provider from the wallet connection component.
const wallet = new BrowserProvider(eip1193Provider);
const writer = new SocialClient(SOCIAL_ADDRESS, await wallet.getSigner());
await writer.verify(CHAIN_ID);
await (await writer.publishPost('Hello from my website')).wait();Clients and types#
| Export | Purpose |
|---|---|
| SocialClient | Independent identity, social graph, posts and likes |
| PlatformClient | Registry Game Discovery |
| GameClient | Read X404 game module state and prepare admission transactions |
| ExtensionsClient / ExtensionAsset / extensionLootAsset | Core asset policies, personal allowances and governance proposals |
| CharactersClient / CharacterKind / AttributeScope | Characters, equipment, categorized inventory, attributes, skills and one participation call |
| HonorClient | Personal mining power, cumulative war reward claims, spending totals and loot sales |
| PvPClient / BattlePermit / PersonalBattle / BattlePage | Personal inventory, battle history, attempt counts and submission of signed claims |
| Country / CountryContributors | Country identity, membership and contribution queries |
| ProfileDetails / ProfileCompletion / PROFILE_FIELDS | Structured profiles, completion status and field bitmap |
| ProtocolContract | Common ABI adaptation for all modules |
| FinanceClient / DexFamily | V2, Infinity CL and Uniswap V4 unified issuance and transaction construction |
| CLLockClient / CLLockDeposit | Create a new liquidity lock for the platform CL pool |
| CLPositionLockClient / LockBeneficiary / LockTranche | Principal, handling fees, shares and unlocking plan |
| TokenLockClient / TokenBeneficiary / TokenTranche / LockTimeUnit | Token amount locks, periodic releases and beneficiary-only extensions |
| IssuanceClient / TeamPlan | Issuance operations, team locks and airdrop funding |
| abis / ContractName | Full ABI and module name types |
| Post / Profile / PostPage / GameEntry | Typed return data |
| metadataURI / identityKey / normalizeUsername | Metadata, stable identification and input validation |
| scanEvents / subscribeEvents / watchEvents / decoder | Event playback, monitoring, confirmation projection and decoding |
| json | JSON serialization of converting bigint to decimal string |
SocialClient API#
const social = new SocialClient(SOCIAL_ADDRESS, providerOrSigner);
await social.verify(CHAIN_ID);
await social.profileId(account);
await social.profileOwner(id);
await social.username(id);
await social.resolveUsername('alice');
await social.profile(account);
await social.followerCount(account);
await social.followingCount(account);
await social.followers(account, 0n, 20);
await social.following(account, 0n, 20);
await social.isFollowing(account, target);
await social.post(id);
await social.posts(0n, 20);
await social.authorPosts(account, 0n, 20);
await social.replies(id, 0n, 20);
await social.liked(id, account);Wallet writing#
const tx = await social.setProfile(metadataURI({name: 'Alice'}), 0n, 'alice');
await tx.wait();
await (await social.setUsername('alice_new')).wait();
await (await social.follow(target)).wait();
await (await social.followBatch([targetA, targetB])).wait();
await (await social.unfollow(target)).wait();
await (await social.unfollowBatch([targetA, targetB])).wait();
await (await social.publishPost('Hello', 0n)).wait();
await (await social.setLike(postId, true)).wait();These methods require a signer and return ethers ContractTransactionResponse. The successful submission of the method does not mean that it has been confirmed. Usewait()After reading the receipt or waiting for the index to reach its block.
The SDK checks the chain ID before every write. Writes work after verify(CHAIN_ID) succeeds, or when CHAIN_ID is passed as the third constructor argument (the fourth for ProtocolContract). If it is missing or differs from the current network, an error is thrown and nothing is sent. Reads do not need it.
Builds, Simulations and Bugs#
const request = social.prepare('publishPost', ['Hello', 0n]);
await provider.call({...request, from: account});
const tx = await signer.sendTransaction(request);
const receipt = await tx.wait();
// Decode the data from ethers call errors with social.decodeError(data).The SDK verifies the number of bytes, username, uint256, paging and batch duplicate addresses. The on-chain check is still the final judgment. Do not rely on simulations or estimates as guarantees: configurations and status may change before trading.
Social Fission Game Module#
const registry = new PlatformClient(REGISTRY_ADDRESS, provider);
const page = await registry.games(0n, 20);
if (page.length === 0) throw new Error('No registered game');
const game = new GameClient(page[0].game, signer, CHAIN_ID);
const request = await game.prepareJoin(inviter, MAX_ENTRY_FEE_WEI);
await (await signer.sendTransaction(request)).wait();prepareJoin reads fees, mining power, tribes, chiefs and sub-ledger wallet hashes in the same block; the chain rejects old quotes when configuration changes. Other game writing methods use the full ABI via prepare/write.
The second argument of prepareJoin, maxFee (wei), is required: it is the most you agree to pay. A game may change its entry fee at any time, and the SDK throws instead of building a transaction when the current fee is higher. Programs that sign automatically should use a fixed limit, not the fee just read from the chain.
Server-side reading#
SDK does not rely on browsers, Next.js or the official website backend. Node.js 20+ can be imported via ESM import or CommonJS require.
import {JsonRpcProvider} from 'ethers';
import {SocialClient, json} from '@x404/sdk';
const provider = new JsonRpcProvider(process.env.RPC_URL);
const social = new SocialClient(process.env.SOCIAL_ADDRESS, provider);
await social.verify(BigInt(process.env.CHAIN_ID));
console.log(json(await social.posts(0n, 20)));
await provider.destroy();Use bigint for protocol integers, and use decimal strings for HTTP JSON, and do not convert them into Numbers that may lose precision.
One index serves multiple users#
import {JsonRpcProvider, WebSocketProvider} from 'ethers';
import {watchEvents, json} from '@x404/sdk';
const http = new JsonRpcProvider(process.env.RPC_URL);
const ws = process.env.WSS_URL
? new WebSocketProvider(process.env.WSS_URL)
: undefined;
const stop = new AbortController();
process.once('SIGINT', () => stop.abort());
await watchEvents(http, [{address: SOCIAL_ADDRESS, kind: 'X404SocialProtocol'}], {
checkpoint: {nextBlock: DEPLOYMENT_BLOCK},
confirmations: 12,
signal: stop.signal,
wakeProvider: ws,
onError: error => console.error(error),
onBatch: async (events, checkpoint) => {
// Production: apply projections idempotently by event.key and save the checkpoint in one database transaction.
console.log(json({events, checkpoint}));
},
});
await ws?.destroy();
await http.destroy();This example only prints events. For a runnable script that saves atomic JSON checkpoints, see Examples. Production databases should commit the projection and cursor in one transaction. Batches may be replayed; if the confirmed chain reorganizes, the scanner throws ReorgError and the application must roll back or rebuild.
To resume scanEvents, pass both fromBlock: savedCheckpoint.nextBlock and checkpoint: savedCheckpoint; watchEvents passes the committed checkpoint automatically. Each scan anchors its target block hash and revalidates both the saved checkpoint and the target anchor before committing each page, so verification calls scale with the number of pages. JSON-RPC header verification and log pagination bypass the short ethers cache. Custom providers must return current canonical-chain data from getBlock(number) and getLogs. Applications must still use a consistent, trusted RPC and handle ReorgError by rolling back and replaying their projections.
Without WSS_URL, watchEvents still reconciles confirmed logs periodically over HTTP. WSS only reduces wakeup latency. This shared index example runs in Node.js; browsers do not need the same subscription.
The watchEvents option intervalMs defaults to 15000 milliseconds and accepts only integers from 100 through 2147483647. Values below the minimum, above the timer limit, fractional values, NaN and Infinity are rejected before any RPC request. This prevents invalid intervals from becoming near-zero timer delays and causing continuous requests. WSS wakeups do not wait for this polling interval.
WSS disconnected#
subscribeEvents delivers immediate, unconfirmed events with the removed flag; it does not automatically save a cursor. watchEvents uses bounded HTTP log scans as its confirmed source, with WSS notifications triggering earlier scans. Scheduled scans continue if WSS fails. The application is responsible for reconnecting its WSS provider; subscriptions alone do not backfill historical logs.
Background signature#
Read-only indexes do not require a private key. If the backend operates its own application role, use explicitly authorized signer, chain ID and nonce management. Giving the backend a private key does not give it the power to modify social status on behalf of the user.
Configuring repo and reading financial logs#
BuybackMode.Burn = 0, BuybackMode.Liquidity = 1;When creating a custom game in
specified in GameSettings.buybackMode . The following takes the local administrator signer as an example; formal deployment should use prepare Generate calldata and hand it over to Safe for multi-signature time lock execution.
import {ProtocolContract, BuybackMode} from '@x404/sdk';
import {parseEther} from 'ethers';
const treasury = new ProtocolContract('X404Treasury', TREASURY_ADDRESS, signer, CHAIN_ID);
// V2 LP tokens typically use 18 decimal places; V4 uses core liquidity units.
// This conversion applies only to V2; do not reuse it for the V4 minimum.
await (await treasury.write('setBuybackMode',
[BuybackMode.Liquidity, parseEther(APPROVED_MINIMUM_LP_PER_BNB)])).wait();
const mode = await treasury.read<bigint>('buybackMode');
const pending = await treasury.read<bigint>('pendingBuybackBNB');Mode changes do not automatically enable or disable circuit breakers. setBuybackPolicy The minimum after-tax purchase of coins still needs to be approved. Use existing scanEvents / watchEvents / subscribeEvents, monitor X404Treasury address of BuybackModeChanged, BuybackLiquidityAdded, BuybackStateUpdated and policies, limit events, maintain pending repurchases, accumulated expenditures and locks LP to avoid repeated reading of getters on an event-by-event basis. Web pages can use HTTP RPC or applications API, Node.js also supports shared WSS indexes.
Unified issuance and transaction interface#
DexFamily.PancakeV2 = 0, PancakeInfinity = 1, UniswapV4 = 2, UniswapV2 = 3. Regular rates default to 2% and can be configured before issuance from 0–5% (0–500 bps), in steps of 0.01%. V2 token.buyTaxBps and token.sellTaxBps are independent; token.poolFeeBps must be 0. The token collects these taxes and the DEX native pool fee is additional. V4 / Infinity CL ordinary buy/sell taxes must be 0; token.poolFeeBps can be 0–500 and is the LP pool fee, collected directly by the DEX core.
Initial rates are selected during creation. After initialization, rate changes require operations proposals and reviewer approval; the creator cannot bypass approval. Rates may be reconfigured before issuance. A rate change increments launchNonce, invalidating old activation requests; an activation proposal must reference the latest approved version and be approved by the reviewer. Rates are immutable after issuance and both pools share the same set. X404GameConfig holds the initial creation terms; read the treasury’s getTokenConfig() for effective current rates.
FinanceClient.prepareTradingFees({buyTaxBps, sellTaxBps, poolFeeBps}) validates the current protocol and integer basis-mining power range, then returns an unsigned request to liquidityManager setTradingFees. Execute it through the game's operation wallet, then re-read launchNonce before preparing activation. DEFAULT_FEE_BPS=200 is the default and MAX_FEE_BPS=500 is the maximum.
V2 collects only its configured buy and sell taxes. Uniswap V4 / Infinity CL uses native static pool fees with a zero Hook address. There is no opening anti-sniping tax or waiting period.
import {FinanceClient, ProtocolContract} from '@x404/sdk';
import {parseEther} from 'ethers';
const finance = new FinanceClient(TREASURY_ADDRESS, signer);
// 游戏配置由运营提交、审核批准执行;配置本身不发行。
const config = await finance.prepareConfigureLaunch({
revenueWallet: REVENUE_WALLET, pools: [{family: await finance.family(), tokens: APPROVED_LIQUIDITY_TOKENS, nativeAmount: APPROVED_NATIVE_BUDGET}],
});
// The current game operation wallet activates the approved version:
const activation = await finance.prepareActivation(APPROVED_NONCE);
await (await managerSigner.sendTransaction(activation)).wait();
const deadline = BigInt((await signer.provider!.getBlock('latest'))!.timestamp + 600);
const buy = await finance.prepareSwap({buy: true, amount: parseEther('0.01'),
minimumOut: APPROVED_MINIMUM_TOKENS, recipient: ACCOUNT, deadline});
await (await signer.sendTransaction(buy)).wait();
const token = new ProtocolContract('X404PlainToken', TOKEN_ADDRESS, signer, CHAIN_ID);
// ERC20 approve also works for V2; the spender is selected automatically as the Router or adapter.
await (await token.write('approve', [await finance.swapSpender(), SELL_TOKENS])).wait();
const sell = await finance.prepareSwap({buy: false, amount: SELL_TOKENS,
minimumOut: APPROVED_MINIMUM_NATIVE, recipient: ACCOUNT, deadline});
await (await signer.sendTransaction(sell)).wait();minimumOut is the application’s final net-output limit; the SDK never relaxes slippage. Amounts are raw base-unit integers. Read the game token’s actual decimals() (default 6, allowed 0–18); native currency has 18 decimals. Approve the V2 router or CL adapter returned by swapSpender() for the exact required amount.
Open Finance and follow the current on-chain state and approval steps. After initialization, operations proposes and the reviewer approves. Check the game, network and wallet before submitting, and wait for confirmation before continuing.
Before issuance, use prepareFeeBeneficiaries to configure V4 fee wallets and shares; the default beneficiary is the game creator. The UI requires an explicit project income wallet for V2 trading taxes and V4 LP fees after the protocol share. Anyone may trigger claims, but cannot redirect payment or withdraw locked principal: first-launch LP is permanently locked by default (or time-locked for a term chosen before launch), and buyback-added LP is always permanently locked. Changing the payout wallet requires the game operation wallet.
After treasury DexLaunched, add the CL adapter to watchEvents and replay the issuance block for initial-liquidity events. For V2 the adapter field is the pair.
adapter.liquidityLock() returns the permanent position vault for that pool. Buyback additions increase the same position without creating more NFTs. Use CLPositionLockClient to settle and claim fees, and watch CLPositionLocked. Personal deposits may still use term locks.
Asset lock access#
CLLockClient.create / prepareCreate Receive platform token budget, minimum actual pool amount, principal wallet, unlocking plan, fee wallet and native currency budget. CLPositionLockClient: collectFees, unlockPrincipal, claimPrincipal, claimFees, claimFeesFor. Anyone may call claimFeesFor(beneficiary, currency, amount) without beneficiary signatures. The protocol share goes to the current platform recipient. For official game CL positions, net income goes to feeRecipient(beneficiary), which operations may propose changing, subject to reviewer approval. Accounting remains keyed by the original beneficiary; shares and claimed balances stay unchanged. Privately created CL/NFT locks still pay their original beneficiaries, and game administrators cannot redirect their income. Claim callers cannot select destinations. Principal rights are unchanged; amount 0 means all currently claimable income. ProtocolContract: ERC20, V2 LP, V4 NFT.
Principal claims and claimFees must be signed by the corresponding beneficiary wallet. Any wallet may trigger claimFeesFor, and net income goes to the original beneficiary’s approved payout address (the original address for private locks). An amount of 0 means all currently claimable funds; future shares cannot be claimed early. Read the ID and vault address from the creation receipt events rather than guessing from the global count. For creation, approval, claims after unlocking and event indexing examples, see Asset locks.
Personal mining power and war distribution#
const honor = await game.honorLedger();
const balance = await honor.goldBalance(wallet); // 1 算力值 = 10^6 原子单位
const claimed = await honor.warGoldClaimed(wallet);
// voucher 来自本游戏的后台 prepare 接口,使用领取者钱包签名提交
await honor.claimWarGold(BigInt(voucher.cumulative), BigInt(voucher.epoch), BigInt(voucher.deadline), voucher.signature);1% of the total reward is shared using the kingdom’s four-tier configuration frozen at war opening, with no per-war cap. The other 99% follows opening battle contributions. The shared pool is not exclusively the king’s; configured tier members need not have battle contributions. Zero-contribution members outside the tiers receive nothing. The backend accumulates confirmed rewards using war-start snapshots; users claim the cumulative difference with its signature. WarGoldReserved records the total reserved for a battle, while WarGoldClaimed records the individual's claimed difference. Country cumulative mining power remains integer mining power and must not be mixed with personal base units. Other mining power sources, such as inventory sales, use their own events without changing this allocation formula.
Configure first, then activate the token and both pools#
const finance = new FinanceClient(TREASURY, signer);
const plan = {
revenueWallet: REVENUE_WALLET, pools: [
{family: DexFamily.PancakeInfinity, tokens: 1_000_000_000n, nativeAmount: parseEther('1')},
{family: DexFamily.UniswapV4, tokens: 500_000_000n, nativeAmount: parseEther('0.5')},
],
};
const config = await finance.prepareConfigureLaunch(plan);
const routing = await finance.prepareBuybackRouting(true);
// The game operation wallet executes config and routing.
// First-launch LP is permanently locked unless a lock term was approved before launch; buyback LP is always permanent.
// The current game operation wallet activates the approved version:
const approvedNonce = await (await finance.liquidityManager()).launchNonce(TREASURY);
const activation = await finance.prepareActivation(approvedNonce);
await (await managerSigner.sendTransaction(activation)).wait();
// 在第二个池子交易:prepareSwap({...swap, poolIndex: 1})。V2 dual pools also use prepareConfigureLaunch: pools set to [{family:DexFamily.PancakeV2,tokens:1_000_000_000n,nativeAmount:parseEther("1")},{family:DexFamily.UniswapV2,tokens:500_000_000n,nativeAmount:parseEther("0.5")}]. The primary pool family must match the creation setting. Reverse the two rows when the other family is primary. Both pools start at the same price; prepareSwap({poolIndex:1,...}) and swapSpender(1) automatically uses the second V2 Router. prepareBuybackRouting(true) rotates after success; false,0/1 fixes the pool. V2 fees accumulate in LP value, with no separate fee-beneficiary configuration.
Asset extensions, countries and inventory#
import {GameClient, ExtensionAsset, extensionLootAsset, identityKey} from '@x404/sdk';
const game = new GameClient(GAME_ADDRESS, signer, CHAIN_ID);
const hub = await game.extensionHub();
const power = await game.points(account); // Lifetime combat power, not spendable gold.
const gold = await hub.assetBalance(account, ExtensionAsset.gold);
const item0 = await hub.assetBalance(account, extensionLootAsset(0));
const countryId = await game.countryMembership(account);
if (countryId !== 0n) {
const country = await game.country(countryId);
const members = await game.countryMembers(countryId, 0n, 20);
const contributors = await game.countryContributors(countryId, 0n, 20);
const key = identityKey(CHAIN_ID, game.address, country.id);
}
const arena = await game.pvpArena();
const inventory = await arena.inventory(account);
const history = await arena.history(account, 0n, 20);
const spent = await (await game.honorLedger()).totalSpentGold();Country pagination uses offset; PvP history returns {battles, total}, starting with the newest battle. BattlePermit uses safe-range numbers for levelA, levelB and draw, and battle reports use a number for aWinBps. Other integer amounts and IDs are bigint. arena.inventoryValue(account) is the integer value of remaining inventory; HonorClient.goldBalance is personal mining power with 6-decimal precision. quoteLootSale also quotes integer mining power. Sell through HonorClient.sellLoot; the credited balance is multiplied by 10^6.
Governance uses prepareConfigureAsset to encode proposals. Gameplay can use await game.characters() / play in one participation transaction without approveAsset; asset calls outside a session still require personal approval bound to the policy version and nonce. Ordinary wallets cannot bypass formal governance. See Game characters and item extensions for permissions and crafting, equipment and country extensions. PvP backend authentication uses pvpAuthMessage; submit operator permits with arena.prepareBattle / battle. See PVP.
For structured profiles and the one-time 10-mining power reward, see Profiles & Metadata. The task hall uses separate HTTP sessions and a contribution ledger. Integrate the Task hall API, rather than GameClient.points.
Issuance, locks and redemption#
Beneficiary amount values must sum to teamAmount; amounts in a nonempty custom schedule must independently sum to the same total. Both SDK and contract validate exact quantities. TokenBeneficiary / TokenTranche use token base units, unlike the LP basis-point types LockBeneficiary / LockTranche. For periodic releases, replace prepareTeamLock with this request to approve the entire plan at once:
const periodicTeamPlan = await issuance.preparePeriodicTeamLock(
teamAmount,
[{ wallet: TEAM_WALLET, amount: teamAmount }],
{ cliffCount: 3, cliffUnit: LockTimeUnit.year,
periodCount: 1, periodUnit: LockTimeUnit.month,
installments: 36, amountPerPeriod: 0n },
);This example locks for 3 years, then releases monthly for 36 installments; the first release occurs 3 years plus 1 month after lock execution. LockTimeUnit supports day / month / quarter / year; months, quarters and years use the UTC calendar. Exactly one of installments and amountPerPeriod must be nonzero. To choose an amount per period, set installments to 0; the final installment releases the remainder.
These are all unsigned requests and must be executed by the authorized governance for each operation. Game configuration is executed by the operation wallet. Do not execute teamExecution before the lock configuration has been confirmed. After funding a pool, use ProtocolContract('X404LiveAirdrop', POOL_ADDRESS, provider) / prepare('scheduleRound', [startsAt, endsAt, expectedRound]) to prepare its schedule request, then have game governance execute it. During the window, users approve and redeem according to the bounded quote from quoteFor. For the full flow, see Timed live airdrops.
Categorized inventory, skills and aggregated battle reads#
Read with the existing game, provider, account, characterId and skillKey:
import {ZeroHash} from 'ethers';
const characters = await game.characters();
const block = await provider.getBlockNumber();
const {entries, total} = await characters.inventory(account, ZeroHash, 0n, 20, block);
const categories = await characters.categoryPage(0n, 20, block);
const learned = await characters.characterSkills(characterId, 0n, 20, block);
const skill = await characters.skill(characterId, skillKey, block);
const arena = await game.pvpArena();
const state = await arena.read('getPlayerState', [account], block);
const fighters = await arena.read('getFighters', [[account]], block);ZeroHash selects all categories. entries distinguishes equipment from item stacks, so always pair IDs with kind. Pages contain 1–100 entries and total counts active entries. Exhausted items are absent, while instances retains history. Pin one block across pages and refresh after writes. skill returns level and readyAt; advancement does not reset cooldown.
Governance proposals use prepareDefineCategory / prepareDefineInventoryType / prepareDefineSkill / prepareSetSkillEnabled; configuration does not automatically grant eligibility to obtain items or skills. Approved modules learn/use skills and consume items within play sessions. getPlayerState / getFighters currently use the inherited generic read, without dedicated SDK wrappers of those names. See PvP for return structures.
Read country tickets with hub.ticket(0) and PvP tickets with hub.ticket(1); activity IDs are not bit flags. Read ticketRecipient() and participate through game.joinCountryWithTicket(...) or arena.battleWithTicket(...). The ERC-20 spender is the hub address, amounts use the token's actual decimals, and transactions bind the current version when enabled or 0 when disabled. Free interfaces cannot bypass a charge. Governance prepares proposals with hub.prepare('configureTicket', [activity, enabled, amount, currency]).
Protocol share of trading income and LP lock policy#
The protocol share of trading income defaults to 25% and may be changed only by platform governance through setTradingFeeShareBps. Each V2 tax conversion and V4/Infinity LP fee claim uses the current rate, including existing games and income accrued before the change but still unclaimed. Already paid income is not recalculated. The share is deducted from trading income, separately from the fixed 1% entry fee; locked principal is never charged. The protocol portion is paid directly to the currently approved Treasury.protocolFees().recipient. Platform Safe multisig and a timelock of at least 1 hour may change it through X404GameFactory.setProtocolFeeRecipient(expectedRecipient, newRecipient). All unpaid protocol BNB, subsequent trading-income payouts and future token tickets use the current address, including existing games. The game portion uses its approved tax or official project LP fee destination; completed payments are not recovered.
First-launch game LP is permanently locked by default. When the platform has enabled timed locks and the game chose a lock term before launch, that LP is time-locked instead: after the unlock time only the game creator wallet can claim it, and the public game page shows the unlock time. Buyback-added LP is always permanently locked. Test deployments (BSC testnet and local chains only) let the creator wallet reclaim LP and are labelled as test deployments on public pages. termLiquidityLocksEnabled only controls new term or installment locks for personally deposited LP and starts enabled. It cannot change game LP or existing locks. Ordinary and team-token vesting is unaffected.
For V4/Infinity, claimableFees, claimedFees, FeesClaimed, and the amount arguments and return values of claimFees / claimFeesFor are gross amounts before the protocol share. Read quoteFees(beneficiary, currency, amount) for (gross, protocolAmount, netAmount, shareBps); amount=0 selects the full current gross entitlement. Game receipts use netAmount. FeesSplit records each gross amount, protocol share, net payment and rate. Fee-wallet weights define the game beneficiaries only and cannot override the protocol destination or rate. Rates and carried fractions may change after a preview; execution events are final.
Fractional protocol fees below one base unit carry forward per contract and currency, so splitting claims cannot avoid the fee. A rejected payment reverts the claim, gross claimed balance and carry, allowing a retry once the receiving issue is resolved. Principal and fee ledgers stay separate.
V2 processTax minimum BNB and TaxConverted amounts describe gross conversion output. The game tax wallet receives the net amount after the protocol share. TaxRevenueSplit records grossBNB / protocolAmount / netAmount / shareBps; income summaries use the actual net amount without counting the gross event again. Forced BNB donations are excluded from conversion income.
Changing payout addresses through multisig#
Team admission destinations, V2 tax wallets and official game CL fee destinations may be changed through operations proposals and reviewer approval for that game. The platform protocol recipient requires the platform Safe timelock; game governance has no such authority. Claims remain permissionless but pay only the currently approved addresses. Private lock beneficiaries, allocation shares and principal rights are unchanged.
- Team admission income: game governance calls
replaceProjectWallet(previousWallet, newWallet)to replace one address atomically, preserving order, headcount and equal shares. Only future admission and takeover payments change. ExistingpendingPaymentsremain owned and claimable by the old account.
- Protocol income: platform governance calls
X404GameFactory.setProtocolFeeRecipient(expectedRecipient, newRecipient). Unpaid protocol BNB, subsequent trading-tax/LP protocol-share payouts and future token tickets use the current address, including existing games. Game governance cannot change it.
- V2 tax income: game governance calls
X404Token.setTaxWallet(expectedWallet, newWallet). Unconverted and future taxes pay the new wallet; completed payments are not recovered. Tax rates and the approved conversion floor remain unchanged.
- Official project CL fees: game governance calls
X404LiquidityManager.setFeeRecipient(vault, originalBeneficiary, expectedRecipient, newRecipient)for a game treasury and original beneficiary. The original ledger identity, shares, claimed balances and principal rights stay unchanged; unpaid net income goes to the new address. One setting applies to all existing and future official project positions in that game;vaultis the game Treasury address. This authority does not apply to privately created CL/NFT locks.
### Treasury BNB disbursements
FinanceClient.prepareDisbursement(recipient, amountWei) only prepares a reviewed disburseBNB call. Amounts are integer wei and the attached value is zero. Operations submits it through the game administration contract; reviewer approval pays from the treasury. This helper never sends transactions or grants direct withdrawal rights. availableDisbursementBNB() excludes pending buyback reserves, and execution checks the balance again. Only newly deployed treasuries support this method.
configureTicket(activity, enabled, amount, currency)
PVP tickets support currency: 0 (mining power with 6 decimals) or currency: 1 (the game token with its actual decimals). Kingdom admission tickets only support tokens. Disabling tickets means free entry; the independent PVP switch still controls challenges. mining power requires no ERC-20 approval.