MAVAN Staking AI Skill
Integrate MAVAN Ethereum staking into custodians, exchanges, and institutional platforms using your existing custody and signing infrastructure.
Use this skill with your AI coding agent to integrate MAVAN Ethereum staking into a custodian, exchange, or institutional platform. It guides engineering teams through backend integration, custody approvals, transaction verification, monitoring, reconciliation, and validator exits using their existing signing infrastructure.
Choose your starting point
| Your task | Start here |
|---|---|
| Integrate with your custody and signing infrastructure | Follow the skill's main implementation path: connect backend API calls and durable operations to your existing approval, signing, and reconciliation systems. |
| Evaluate the examples before onboarding | Install the package and run the credential-free fixture tests below. |
| Build a status or rewards dashboard | Use the skill's read-only workflow with an account-authorized backend. |
| Recover interrupted operations or manage exits | Reconcile saved stake and signing-job state, verify the payload and fee budgets, and continue through your existing approval workflow. |
For API access, you need a MAVAN account and an API key for the chosen environment. Creation and exit crafting require staker permission and account readiness. Signing requires your authorized custody or signing service, a matching-chain RPC, and approved request-fee and gas budgets. Keep API keys on the backend and private signing material inside the signing system.
Download the complete package as Markdown. This snapshot contains five files: SKILL.md, two reusable helpers, and two credential-free test files. The examples require Node.js 22+ and viem; the tests use Node's built-in test runner. The snapshot version is recorded in SKILL.md.
Optional browser-wallet reference
The package includes an EIP-1193 browser-wallet example to demonstrate transaction verification and signing. Use it when your application explicitly requires browser signing. For institutional integrations, adapt its verification checks to your custody or signing service and implement that service's approval and job-reconciliation workflow. The example is not a provider-specific custody SDK.
Install in your project
Run these commands from your application project. They extract only the five named files. Choose the copy command for your editor. To test an unpublished ReadMe branch, replace the download URL with that branch's Markdown page URL.
curl --fail --silent --show-error \
https://docs.mavan.bitminetech.io/docs/integrate-mavan-staking.md \
--output mavan-staking-skill.md
python3 - <<'PY'
import re
from pathlib import Path
source = Path("mavan-staking-skill.md").read_text()
allowed = {"SKILL.md", "scripts/mavan-api.mjs", "scripts/ethereum-wallet.mjs", "scripts/mavan-api.test.mjs", "scripts/ethereum-wallet.test.mjs"}
pattern = r"^## (SKILL\.md|scripts/[a-z.-]+\.mjs)\n+(" + chr(96) + r"{3,})[^\n]*\n(.*?)\n\2[ \t]*$"
matches = re.findall(pattern, source, re.M | re.S)
files = {name: content for name, fence, content in matches}
if len(matches) != len(allowed) or set(files) != allowed:
raise SystemExit("Incomplete skill download; no files were installed")
for name, content in files.items():
target = Path("integrate-mavan-staking") / name
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(content + "\n")
print("Installed integrate-mavan-staking/")
PY
# Cursor: run from your application project
mkdir -p .cursor/skills
cp -R integrate-mavan-staking .cursor/skills/
# Claude Code: run from your application project
mkdir -p .claude/skills
cp -R integrate-mavan-staking .claude/skills/Invoke /integrate-mavan-staking or ask your agent to use this skill for the selected workflow.
Run the credential-free checks
Install viem using your application's package manager if it is not already a dependency. From the application project, run:
node --test integrate-mavan-staking/scripts/*.test.mjsThe fixtures validate deposits and independently quoted exits, reject altered transactions and excessive fees, and exercise batch-deposit recovery and scoped rewards. Every API and wallet call is mocked: no account, API key, RPC connection, or funded wallet is needed. Passing these checks validates the examples; follow the skill's scope-specific acceptance run to validate your application against the real deployment.
Update an installed copy
Download and extract the current package again, compare its SKILL.md snapshot version and changes with your installed copy, then copy the complete folder to your editor's skill directory. Preserve any local adaptations before replacing files. Check the deployment's /docs-json and your installed dependencies before adopting an update.
SKILL.md
---
name: integrate-mavan-staking
description: >
Integrate MAVAN Ethereum staking into custodians, exchanges, and institutional platforms: custody approvals and signing, Pectra creation and funding, status and rewards, recovery, and full exits. Use for implementing these application workflows with existing signing infrastructure; other networks and liquid staking use separate flows.
compatibility: Node.js 22+ and viem for the examples and tests; an EIP-1193 wallet only for the optional browser-signing reference.
metadata:
version: "2026-10-19"
---
# Integrate MAVAN staking
Use this skill as an engineering team at a custodian, exchange, or institutional platform integrating MAVAN staking into your existing infrastructure. The main path connects backend API calls, custody approvals, transaction verification, monitoring, reconciliation, and validator exits. The package supplies API and verification examples; map approval and signing to your existing service's documented interfaces.
## Select the requested workflow
Inspect the existing framework, backend authorization, durable storage, custody or signing integration, and installed dependencies before editing. Preserve those choices and establish the authorized API environment. Ask only for prerequisites that cannot be found in the project or supplied configuration.
| Requested outcome | Implementation scope |
| --- | --- |
| Integrate with your custody and signing infrastructure | Backend API calls and durable operations connected to the existing approval, signing, webhook/polling, and reconciliation workflow. Use this as the main staking implementation path. |
| Status or rewards dashboard | Account-authorized reads, validator status, explicitly scoped rewards, and unit formatting. Signing, stake creation, and exits are outside this scope. |
| Recover an interrupted operation | Reconcile saved stake, signing job, and transaction state; resume the existing operation. |
| Selected-validator exits | Verify each validator and its withdrawal address, enforce fee budgets, submit only selected exits, and track eventual withdrawal. |
For a credential-free introduction, run `node --test scripts/*.test.mjs` from this skill directory after installing the examples' `viem` dependency. These deterministic fixtures exercise the helpers; they do not contact MAVAN or complete on-chain staking.
For API access, provision an account and an environment-specific key with the permissions required for the selected workflow. Signing also requires an authorized custody or signing service, an RPC on the same chain, durable operation storage, and an application policy for confirmation/finality and fee budgets. Funded acceptance additionally requires the selected stake amount and sufficient ETH for transaction fees. Keep API keys in server-side secrets and signing keys within the signing system.
This package snapshot is dated 2026-10-19. Check the configured deployment's current API schema and the application's installed `viem` version before using it; the snapshot date is not an API version or a claim of compatibility with every future release.
## API contract
Read the configured deployment's `/docs-json` when checking API behavior; its DTOs can mark runtime-optional fields as required, so the examples supply them explicitly.
Set `baseUrl` in `createMavanClient` to the API origin configured for the integration:
- `https://api.mavan.bitminetech.io`
- `https://testnetapi.mavan.bitminetech.io`
Read `GET /public/networkConfig` from that origin and use `ethereum.chainId` and the returned contract addresses to configure signing and verification. Use an API key and account provisioned for that same API origin.
Authenticate backend requests with the `api-key` header. Keep API keys in server-side secrets; expose only account-authorized staking data and unsigned transactions to the frontend. The API usually returns `{ "data": ... }`; the bundled client unwraps `data` exactly once.
| Task | Request | Result under `data` |
| ---------------------------------- | ----------------------------------------------- | -------------------------------------------------------------- |
| Authenticate | `GET /account` | Account, including `kycStatus` and `mnemonicStatus` |
| Network and contracts | `GET /public/networkConfig` (public) | `ethereum.chainId`, `network`, and contract addresses |
| Create Pectra stake | `POST /ethereum/stakeV3` | `{ stake: { stakeId, validators, ... }, transaction }` |
| Read this stake | `GET /ethereum/stake/{stakeId}` | Stake with `validators[]`, directly |
| Reconcile by application reference | `GET /ethereum/stakes?reference=...` | Stake array; reference is a filter, not a uniqueness guarantee |
| Rewards | `GET /ethereum/validators/dailyRewards` | Array of daily reward records |
| Craft full exit | `POST /ethereum/txcrafting/validators/withdraw` | Unsigned transaction with analysis |
Use `staker` permission for creation and exit crafting. For staking operations, the account must have `kycStatus: KYC_APPROVED` and `mnemonicStatus: ACTIVE`. The latter is an account readiness flag: never request, generate, or transmit the customer's private wallet keys or mnemonic for these examples. Obtain the environment-specific API key from [MAVAN Command Center settings](https://app.mavan.bitminetech.io/settings).
## Implement the lifecycle
Apply the steps needed by the selected workflow. A complete staking integration covers the entire lifecycle; a read-only implementation uses status and reward handling without creating or signing transactions.
1. Use `getAccount()` and `getNetworkConfig()` for read-only preflight. Check permissions and account readiness for the selected workflow; match the API's Ethereum chain ID to the wallet/custodian and RPC before signing.
2. Persist the application operation, a unique `reference`, the exact creation body, and a UUID v4 `x-request-id` **before** sending a creation request. Use this body, substituting the customer's addresses:
```json
{
"withdrawalAddress": "0x1111111111111111111111111111111111111111",
"suggestedFeeRecipient": "0x1111111111111111111111111111111111111111",
"fromAddress": "0x1111111111111111111111111111111111111111",
"stakeAmountGwei": "32000000000",
"maxEthPerValidatorGwei": "2048000000000",
"reference": "app-stake-operation-123"
}
```
Addresses above are illustrative; do not submit them. Use decimal strings for amounts: 32 ETH = `32000000000` gwei = `32000000000000000000` wei. `maxEthPerValidatorGwei` sets the allocation cap; validators can contain differing amounts. Omit `region` unless the user has chosen an available deployment region.
3. Persist `data.stake.stakeId`, validator pubkeys, the body, request ID, and deposit transaction. A successful create call reserves validators; it does not fund or activate them. `transaction` can be null even when a stake exists. Recover the existing stake and craft a batch deposit with `/ethereum/txcrafting/validators/batchdeposit`; do not create another stake to recover a missing transaction.
4. Validate the returned transaction, then submit it through the institution's authorized approval and signing workflow. Adapt the checks in [the verification and browser-signing reference](scripts/ethereum-wallet.mjs) to compare chain, destination, amount, and encoded deposits with the expected inputs and enforce an explicit maximum gas cost (`gas * maxFeePerGas`). Verify withdrawal credentials and fee recipient; surface `analysis.observations` and simulations. Keep `value`, gas, and fee values as `BigInt` when preparing a transaction. Persist its signing-job ID and transaction hash as they become available, and check the receipt before another send. Never send the `analysis` object as transaction calldata. See the custody and signing infrastructure section for the field mapping and approval lifecycle.
5. Poll the stake with a bounded wait and increasing intervals. Read each validator's `status`; a stake's status alone is insufficient. Typical progress is `WAITING_DEPOSIT` → `PENDING_ACTIVATION` → `ACTIVE`, with other key-generation and deployment states possible. `ACTIVE_EXITING`, `EXITING_SLASHED`, `EXITED`, `EXITED_SLASHED`, and `ABANDONED` require distinct UI states. Timeouts should preserve the stake ID and transaction hash for resumption. Activation depends on the network queue.
6. Once validators have numeric indexes, request rewards with **singular** `validatorIndex` containing comma-separated indexes, `dateFrom` / `dateTo` in Unix **seconds**, `version=v2`, and `timezone=Etc/UTC`. Do not omit the indexes when displaying a single stake: omission can return account-wide rewards. For v2, `consensusRewards` and `executionRewards` are wei strings; format ETH with `formatUnits(BigInt(value), 18)` and preserve the raw strings. An empty array can mean no indexed rewards yet. Do not invent rewards or a fixed yield.
7. For each active validator selected for a full exit, craft this body from its actual pubkey and withdrawal wallet:
```json
{
"fromAddress": "0x1111111111111111111111111111111111111111",
"validatorPubkey": "0x<48-byte-validator-public-key>",
"amountGwei": "0",
"gasEstimateMultiplier": 1.2
}
```
Here `amountGwei: "0"` requests a **full exit**. Transaction `value` pays the on-chain withdrawal-request fee. Refresh the request-fee quote from the withdrawal contract on the expected chain before signing. Verify the transaction value against that independent quote and an explicit user/application maximum; deriving the expected fee from the transaction itself provides no protection against overpayment. Use `await exitExpectations(validatorPubkey, withdrawalAddress, networkConfig.ethereum, { rpc, maxExitRequestFeeWei })` with a trusted read-only RPC provider for that chain. Enforce a separate maximum gas cost (`gas * maxFeePerGas`) in the signing integration, as demonstrated by `sendMavanTransaction`, and repeat verification after approval delays or replacement payloads. If the quote and payload differ, re-craft and review the payload before approval. The request fee can still change before inclusion: increases can cause a revert, and excess payment after a decrease is not refunded. Reconcile any failed transaction before retrying.
The withdrawal address must sign and broadcast it. Check its receipt, then resume status polling through exit and withdrawal eligibility. An exit transaction receipt or `EXITED` status does not prove that ETH has arrived; reconcile the withdrawal address's on-chain receipt/balance separately. The destination remains the validator's withdrawal address. Repeat only for the explicitly selected validators.
## Integrate with your custody and signing infrastructure
Keep MAVAN API calls on the backend and submit the verified unsigned transaction through your existing custody or signing service. Implement the service's documented approvals, signing-job states, and reconciliation. The package does not include a provider-specific custody adapter.
Adapt the transaction checks implemented in `sendMavanTransaction` to run before submitting a custody signing job; its `eth_requestAccounts` and `eth_sendTransaction` calls belong to the optional browser reference. Reuse `depositExpectations` and asynchronous `exitExpectations` with the `ethereum` object returned by network config, a trusted chain RPC for exit-fee reads, and the same explicit request-fee and gas budgets.
Map the transaction into the custodian's documented contract-call request:
| MAVAN field | Custodian mapping |
| --- | --- |
| `chainId` | Custodian network or asset identifier mapped from `networkConfig.ethereum.chainId`; check the source wallet and RPC use that chain. |
| `fromAddress` | Customer-authorized source wallet, vault, or signing account. For a full exit, use the validator's withdrawal address. |
| `to` | Contract destination; compare with the expected deposit or withdrawal contract from network config. |
| `data` | Exact hexadecimal calldata, including the `0x` prefix. |
| `value` | Native ETH amount in wei. Convert units only if required by the custodian API, using exact decimal strings. |
| `gas`, `maxFeePerGas`, `maxPriorityFeePerGas` | Gas limit and fee values in the custodian's documented units. Refresh estimates after long approval waits. Let the custodian manage the current nonce. |
Persist the application operation and the custodian's request or job ID before waiting for approval. Track approval, rejection, failure, broadcast, and confirmation separately from MAVAN validator status. Verify webhook authenticity using the custodian's documented mechanism, or poll its job API. Persist the transaction hash as soon as broadcast occurs and confirm its receipt on the expected chain.
Use the custodian's documented idempotency mechanism when submitting a signing job. After a timeout or restart, reconcile the existing job and transaction before submitting another. If approval delays require a replacement payload, refresh gas and fees, repeat transaction verification, and obtain the approval required by the custodian's policy for the changed payload. Resume staking progress from the saved stake ID and transaction hash.
## Recover a missing deposit transaction
When stake creation succeeded but `transaction` is null, recover the saved stake with `GET /ethereum/stake/{stakeId}`. If the creation response was lost, reconcile `GET /ethereum/stakes?reference=...` against the persisted creation body and addresses to identify the existing stake. Confirm that no deposit has already been broadcast or confirmed before crafting another transaction; reconcile any custodian job and transaction hash first.
Send `POST /ethereum/txcrafting/validators/batchdeposit` with the backend `api-key` header and `Content-Type: application/json`. Use the bundled backend client's `craftBatchDeposit(input)` method, which applies the same request and response handling. The request body is:
```json
{
"fromAddress": "0x1111111111111111111111111111111111111111",
"gasEstimateMultiplier": 1.2,
"deposits": [
{
"validatorPubkey": "0x<48-byte-validator-public-key>",
"amountWei": "32000000000000000000",
"signature": "0x<96-byte-deposit-signature>",
"withdrawalCredentials": "0x0200000000000000000000001111111111111111111111111111111111111111"
}
]
}
```
Build this body from the recovered stake and persisted creation request, replacing every illustrative value:
- `fromAddress`: the original funding address, matched to the custodian source wallet.
- `deposits`: one entry per validator in the recovered, unfunded stake, retaining the returned order.
- `validatorPubkey`, `signature`, `withdrawalCredentials`: the validator's `pubkey`, `signature`, and `withdrawal_credentials`, normalized to hexadecimal strings with a `0x` prefix.
- `amountWei`: `BigInt(validator.amount) * 1_000_000_000n`, converted to a decimal string; the validator's `amount` is in gwei. Use each validator's actual allocation.
Unwrap the response's `data` once to obtain the transaction and its `analysis`. Check that the deposit amounts sum to the persisted `stakeAmountGwei` converted to wei. Reuse `depositExpectations({ stake, transaction }, creationBody, networkConfig.ethereum)` and the transaction checks before submitting the recovered payload for custody approval. Persist it against the existing stake ID, then continue the same deposit and status workflow.
## Retry and error behavior
`x-request-id` is supported by stake creation and operator-managed bulk exits; it is not a generic idempotency header for every endpoint. Reuse it only for the same method, path, and body. Successful responses are replayed; changed payloads or in-progress requests can return `409`. Records have a 24-hour TTL. Do not treat that retention as permanent duplicate protection. Persist application state and reconcile `/ethereum/stakes?reference=...` and transaction hashes after ambiguous failures, before resending. Creation errors are not guaranteed to be cached.
Do not retry `400` / `401` / `403` unchanged. Inspect account readiness, permissions, address validation, and IP restrictions. For read requests, bounded retries for `429` and transient `5xx` are reasonable; respect `Retry-After` when present. The bundled client makes one request per call and reports HTTP status and body via `MavanApiError`.
Operator-managed `/ethereum/bulkWithdrawValidators` is an alternative exit flow, not the default for this Pectra integration. It takes `{ "pubkeys": [...] }`, immediately attempts exit broadcasts, returns a **per-validator error array**, and is unavailable when encrypted exit messages are enabled. An HTTP success is not proof that every validator exited. Do not substitute this endpoint silently.
## Optional browser-wallet reference
Use [the browser-wallet example](scripts/ethereum-wallet.mjs) only when the application requires EIP-1193 browser signing. It demonstrates verification before wallet access and transaction submission. Pass an explicit `{ maxGasCostWei }` budget to `sendMavanTransaction(provider, transaction, expected, { maxGasCostWei })`; exits also require the independent RPC quote and request-fee budget described above. Browser signing is optional for the institutional implementation path.
## Reusable examples and completion
Use [the backend client](scripts/mavan-api.mjs) with Node.js 22+ and adapt the verification examples to the application's server-side authorization, durable storage, and existing signing service. Implement and validate the service-specific approval and reconciliation paths alongside these helpers.
Run the credential-free helper checks described above, then validate the application changes appropriate to the selected workflow. Include response parsing, rejected or wrong-network signing, altered payloads, excessive fees, missing deposit payloads, and ambiguous broadcasts when those paths are in scope.
Finish with a concise report: implemented workflow and files, API origin and chain, readiness checks, tests actually run, and outstanding prerequisites or acceptance steps. Distinguish fixture results, live read results, transaction receipts, validator activation, and completed withdrawals. Report pending network stages with the saved operation identifiers and resumption step; never describe a fixture run or an exit-request receipt as a completed staking lifecycle.
## Acceptance run
Match acceptance to the requested scope. For reporting, verify authorized account/stake access, status mapping, validator-index filtering, empty rewards, and exact wei-to-ETH formatting; no funded transaction is required. For recovery or exits, validate the relevant existing operation and record its resulting state. For a full staking integration, use the funded lifecycle below before claiming end-to-end acceptance. If credentials, approval, funds, or network progress are unavailable, complete the local implementation and checks, then report the remaining acceptance steps precisely.
Validate the integration with the chosen wallet or custodian's actual signing workflow on the configured deployment before rollout. Use an onboarded account, its `staker` API key, and authorized funding and withdrawal addresses. Fund the source wallet with at least the selected stake amount plus gas; keep enough ETH at the withdrawal address for the later exit request fee and gas. Check the deployment's `/docs-json` before the run.
1. Record the API version, chain ID, contract addresses, source and withdrawal addresses, and wallet or custodian network configuration. Verify account readiness and create a 32 ETH Pectra stake with a persisted reference, creation body, and request ID.
2. Validate the deposit payload, complete the configured approval and signing flow, and record the on-chain transaction hash plus custodian job ID where applicable. Verify a successful receipt and the application's configured confirmation or finality threshold. A successful custody job alone is insufficient.
3. Restart the integration and demonstrate resumption from persisted state without a second stake creation or deposit. Poll until the validator becomes `ACTIVE` and has a numeric validator index; allow for the network activation queue.
4. Query v2 rewards for that validator index and a completed UTC reward period. Retain the raw wei values and verify their parsing and displayed units. If data is not yet available, resume after the reward period and data sync rather than treating an empty response as a completed rewards check.
5. Craft `amountGwei: "0"` for the selected validator, refresh the independent withdrawal-request fee quote, verify the full-exit payload against the request-fee and gas budgets, and complete the withdrawal address's signing flow. Record the exit transaction and successful receipt, then track exit and withdrawal progress. Verify the eventual consensus-layer withdrawal to the expected address; account for unrelated transfers and gas when using balance reconciliation.
6. Keep a run record linking the application operation, MAVAN stake ID, validator pubkey and index, custody job IDs where applicable, deposit and exit hashes, confirmed receipts, rewards response, and withdrawal evidence. Complete the run when all lifecycle steps and restart recovery have recorded results. Keep API keys and private signing material out of this record.
Alongside the funded run, cover a missing deposit payload, rejected custody approval, wrong network, altered destination or calldata, and ambiguous broadcast timeout with deterministic tests. Keep the evidence for those tests distinct from the chain receipts and withdrawal evidence in the acceptance record.
References: [API environments](https://docs.mavan.bitminetech.io/docs/introduction), [authentication](https://docs.mavan.bitminetech.io/docs/authentication-1), [validator statuses](https://docs.mavan.bitminetech.io/docs/validator-statuses), [payload verification](https://docs.mavan.bitminetech.io/docs/transaction-payload-verification), the configured deployment's `/docs-json`.scripts/mavan-api.mjs
/** Backend-only MAVAN client. Requires Node.js 22 or later. */
export class MavanApiError extends Error {
constructor(status, body) {
super(`MAVAN API returned HTTP ${status}`);
this.name = 'MavanApiError';
this.status = status;
this.body = body;
}
}
export function createMavanClient({
apiKey,
baseUrl,
fetchImpl = globalThis.fetch,
}) {
if (!apiKey) throw new Error('Supply the API key from a server-side secret');
if (!baseUrl)
throw new Error(
'Supply the MAVAN API origin configured for this integration',
);
const base = new URL(baseUrl);
if (
base.protocol !== 'https:' ||
base.pathname !== '/' ||
base.search ||
base.hash ||
base.username ||
base.password
) {
throw new Error('baseUrl must be an HTTPS API origin');
}
async function request(
path,
{ method = 'GET', body, requestId, query, authenticated = true } = {},
) {
const url = new URL(path, base);
const headers = { Accept: 'application/json' };
if (authenticated) headers['api-key'] = apiKey;
if (body !== undefined) headers['Content-Type'] = 'application/json';
if (requestId) headers['x-request-id'] = requestId;
for (const [name, value] of Object.entries(query ?? {})) {
if (value !== undefined) url.searchParams.set(name, String(value));
}
// Deliberately make one attempt. The caller controls reconciliation and retries.
const response = await fetchImpl(url, {
method,
headers,
body: body === undefined ? undefined : JSON.stringify(body),
signal: AbortSignal.timeout(30_000),
});
const text = await response.text();
let payload;
try {
payload = JSON.parse(text);
} catch {
if (!response.ok)
throw new MavanApiError(response.status, {
message: 'Non-JSON response',
});
throw new Error('Expected a JSON API response');
}
if (!response.ok) throw new MavanApiError(response.status, payload);
if (!payload || !Object.hasOwn(payload, 'data'))
throw new Error('Expected an API data envelope');
return payload.data;
}
function stakePath(stakeId) {
if (!Number.isSafeInteger(stakeId) || stakeId < 1)
throw new Error('stakeId must be a positive integer');
return `/ethereum/stake/${stakeId}`;
}
return {
getAccount: () => request('/account'),
getNetworkConfig: () =>
request('/public/networkConfig', { authenticated: false }),
createStake: (input, requestId) => {
if (!requestId)
throw new Error('Persist a request ID before creating a stake');
return request('/ethereum/stakeV3', {
method: 'POST',
body: input,
requestId,
});
},
craftBatchDeposit: (input) =>
request('/ethereum/txcrafting/validators/batchdeposit', {
method: 'POST',
body: input,
}),
getStake: (stakeId) => request(stakePath(stakeId)),
findStakes: (reference) =>
request('/ethereum/stakes', { query: { reference } }),
getRewards: (
validatorIndexes,
{ dateFrom, dateTo, currency = 'USD' } = {},
) => {
if (
!validatorIndexes?.length ||
!validatorIndexes.every(
(index) => Number.isSafeInteger(index) && index >= 0,
)
) {
throw new Error(
'Supply explicit non-negative validator indexes for this stake',
);
}
if (
![dateFrom, dateTo].every(
(value) => Number.isSafeInteger(value) && value >= 0,
) ||
dateFrom >= dateTo
) {
throw new Error('Supply an increasing date range in Unix seconds');
}
return request('/ethereum/validators/dailyRewards', {
query: {
validatorIndex: validatorIndexes.join(','),
dateFrom,
dateTo,
currency,
version: 'v2',
timezone: 'Etc/UTC',
},
});
},
craftFullExit: ({ fromAddress, validatorPubkey }) =>
request('/ethereum/txcrafting/validators/withdraw', {
method: 'POST',
body: {
fromAddress,
validatorPubkey,
amountGwei: '0',
gasEstimateMultiplier: 1.2,
},
}),
};
}scripts/ethereum-wallet.mjs
/** Browser wallet example. Install viem in your application. Never supply API keys here. */
import { encodeFunctionData } from 'viem';
const batchDepositAbi = [
{
type: 'function',
name: 'batchDeposit',
stateMutability: 'payable',
outputs: [],
inputs: [
{
name: '_deposits',
type: 'tuple[]',
components: [
{ name: 'pubKey', type: 'bytes' },
{ name: 'withdrawalCredentials', type: 'bytes' },
{ name: 'signature', type: 'bytes' },
{ name: 'amount', type: 'uint256' },
],
},
],
},
];
const hex = (value) => `0x${String(value).replace(/^0x/i, '').toLowerCase()}`;
const quantity = (value) => `0x${BigInt(value).toString(16)}`;
const address = (value) => {
if (!/^0x[\da-f]{40}$/i.test(value))
throw new Error('Expected a 20-byte Ethereum address');
return value.toLowerCase();
};
/** Derive signing expectations from the requested stake and every returned validator. */
export function depositExpectations(created, input, config) {
if (!created.transaction)
throw new Error(
'Stake exists but deposit transaction is unavailable; recover this stake',
);
const validators = created.stake?.validators;
if (!validators?.length) throw new Error('No validators returned');
if (
address(created.stake.withdrawalAddress) !==
address(input.withdrawalAddress)
)
throw new Error('Withdrawal address mismatch');
const credentials = `0x02${'0'.repeat(22)}${address(input.withdrawalAddress).slice(2)}`;
const deposits = validators.map((validator) => {
if (hex(validator.withdrawal_credentials) !== credentials)
throw new Error('Validator withdrawal credentials mismatch');
if (
address(validator.suggestedFeeRecipient) !==
address(input.suggestedFeeRecipient)
)
throw new Error('Fee recipient mismatch');
if (
!/^0x[\da-f]{96}$/i.test(hex(validator.pubkey)) ||
!/^0x[\da-f]{192}$/i.test(hex(validator.signature))
) {
throw new Error('Invalid validator public key or deposit signature');
}
return {
pubKey: hex(validator.pubkey),
withdrawalCredentials: credentials,
signature: hex(validator.signature),
amount: BigInt(validator.amount) * 1_000_000_000n,
};
});
const valueWei = BigInt(input.stakeAmountGwei) * 1_000_000_000n;
if (
deposits.reduce((total, deposit) => total + deposit.amount, 0n) !== valueWei
)
throw new Error(
'Validator deposit amounts do not match the requested stake',
);
return {
chainId: config.chainId,
fromAddress: input.fromAddress ?? input.withdrawalAddress,
toAddress: config.pectraBatchDepositContractAddress,
valueWei,
data: encodeFunctionData({
abi: batchDepositAbi,
functionName: 'batchDeposit',
args: [deposits],
}),
};
}
/** Refresh the fee using a trusted read-only RPC immediately before requesting approval. */
export async function exitExpectations(
validatorPubkey,
withdrawalAddress,
config,
{ rpc, maxExitRequestFeeWei } = {},
) {
const pubkey = hex(validatorPubkey);
if (!/^0x[\da-f]{96}$/i.test(pubkey))
throw new Error('Expected a 48-byte validator public key');
if (maxExitRequestFeeWei == null || BigInt(maxExitRequestFeeWei) <= 0n)
throw new Error('Set an approved positive maximum exit request fee in wei');
if (!rpc?.request) throw new Error('Supply a trusted read-only Ethereum RPC');
if (
BigInt(await rpc.request({ method: 'eth_chainId' })) !==
BigInt(config.chainId)
)
throw new Error('Fee RPC chain mismatch');
const toAddress = address(config.ethValidatorWithdrawalContractAddress);
// EIP-7002: empty calldata returns the current fee as a 32-byte integer.
const fee = await rpc.request({
method: 'eth_call',
params: [{ to: toAddress, data: '0x' }, 'latest'],
});
if (!/^0x[\da-f]{64}$/i.test(fee) || BigInt(fee) <= 0n)
throw new Error('Withdrawal request fee is unavailable');
const valueWei = BigInt(fee);
if (valueWei > BigInt(maxExitRequestFeeWei))
throw new Error('Current exit request fee exceeds the approved maximum');
return {
chainId: config.chainId,
fromAddress: withdrawalAddress,
toAddress,
// This quote can change before inclusion. Overpayment is not refunded.
valueWei,
// Full-exit calldata: a 48-byte public key followed by a zero uint64 amount.
data: `${pubkey}${'0'.repeat(16)}`,
};
}
/** Call from an explicit user action after displaying the transaction and analysis. */
export async function sendMavanTransaction(
provider,
transaction,
expected,
{ maxGasCostWei } = {},
) {
if (!provider?.request) throw new Error('Connect an EIP-1193 wallet');
if (!transaction || transaction.chainId !== expected.chainId)
throw new Error('Transaction chain mismatch');
if (address(transaction.to) !== address(expected.toAddress))
throw new Error('Transaction destination mismatch');
if (
BigInt(transaction.value) !== BigInt(expected.valueWei) ||
BigInt(transaction.value) < 0n
)
throw new Error('Transaction value mismatch');
if (hex(transaction.data) !== hex(expected.data))
throw new Error('Transaction calldata mismatch');
if (
BigInt(transaction.gas) <= 0n ||
BigInt(transaction.maxPriorityFeePerGas) < 0n ||
BigInt(transaction.maxFeePerGas) < BigInt(transaction.maxPriorityFeePerGas)
) {
throw new Error('Invalid transaction gas or fees');
}
if (maxGasCostWei == null || BigInt(maxGasCostWei) <= 0n)
throw new Error('Set an approved positive maximum gas cost in wei');
if (
BigInt(transaction.gas) * BigInt(transaction.maxFeePerGas) >
BigInt(maxGasCostWei)
)
throw new Error('Maximum transaction gas cost exceeds the approved budget');
const analysis = transaction.analysis;
if (!Array.isArray(analysis?.observations))
throw new Error('Transaction analysis is unavailable');
if (
analysis.observations.some((item) => item.severity === 'danger') ||
Object.values(analysis.simulations ?? {}).some(
(simulation) => simulation.success === false,
)
) {
throw new Error('Resolve the transaction analysis failure before signing');
}
const chainId = Number(
BigInt(await provider.request({ method: 'eth_chainId' })),
);
if (chainId !== expected.chainId)
throw new Error('Switch the wallet to the API network');
const accounts = await provider.request({ method: 'eth_requestAccounts' });
if (!accounts[0] || address(accounts[0]) !== address(expected.fromAddress))
throw new Error('Select the expected funding or withdrawal wallet');
// Let the wallet choose a current nonce; the API nonce is only an estimate.
return provider.request({
method: 'eth_sendTransaction',
params: [
{
from: accounts[0],
to: transaction.to,
data: transaction.data,
value: quantity(transaction.value),
gas: quantity(transaction.gas),
chainId: quantity(transaction.chainId),
maxFeePerGas: quantity(transaction.maxFeePerGas),
maxPriorityFeePerGas: quantity(transaction.maxPriorityFeePerGas),
},
],
});
}
export async function waitForReceipt(
provider,
hash,
{ timeoutMs = 120_000, pollMs = 3_000 } = {},
) {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
const receipt = await provider.request({
method: 'eth_getTransactionReceipt',
params: [hash],
});
if (receipt) {
if (BigInt(receipt.status) !== 1n)
throw new Error(
'Transaction reverted; inspect the receipt before retrying',
);
return receipt;
}
await new Promise((resolve) => setTimeout(resolve, pollMs));
}
throw new Error(
'Transaction is still pending; keep the hash and reconcile it before sending again',
);
}scripts/mavan-api.test.mjs
import assert from 'node:assert/strict';
import test from 'node:test';
import { createMavanClient, MavanApiError } from './mavan-api.mjs';
test('recover a deposit with the existing validators and unwrap data once', async () => {
const input = {
fromAddress: `0x${'11'.repeat(20)}`,
gasEstimateMultiplier: 1.2,
deposits: [
{
validatorPubkey: `0x${'22'.repeat(48)}`,
signature: `0x${'33'.repeat(96)}`,
withdrawalCredentials: `0x02${'0'.repeat(22)}${'11'.repeat(20)}`,
amountWei: '32000000000000000000',
},
],
};
let calls = 0;
const transaction = { data: '0x1234', value: input.deposits[0].amountWei };
const client = createMavanClient({
apiKey: 'fixture-not-a-real-key',
baseUrl: 'https://mavan.example',
fetchImpl: async (url, options) => {
calls++;
assert.equal(
url.pathname,
'/ethereum/txcrafting/validators/batchdeposit',
);
assert.equal(options.method, 'POST');
assert.deepEqual(JSON.parse(options.body), input);
assert.equal(options.headers['api-key'], 'fixture-not-a-real-key');
assert.equal(options.headers['x-request-id'], undefined);
return Response.json({ data: transaction });
},
});
assert.deepEqual(await client.craftBatchDeposit(input), transaction);
assert.equal(calls, 1);
});
test('public network lookup and scoped rewards use the expected parameters', async () => {
const calls = [];
const client = createMavanClient({
apiKey: 'fixture-not-a-real-key',
baseUrl: 'https://mavan.example',
fetchImpl: async (url, options) => {
calls.push({ url, options });
return Response.json({ data: [] });
},
});
await client.getNetworkConfig();
assert.equal(calls[0].options.headers['api-key'], undefined);
assert.throws(() => client.getRewards([], { dateFrom: 1, dateTo: 2 }));
assert.equal(calls.length, 1);
await client.getRewards([1, 2], { dateFrom: 1, dateTo: 2 });
assert.equal(calls[1].url.searchParams.get('validatorIndex'), '1,2');
assert.equal(calls[1].url.searchParams.get('version'), 'v2');
assert.equal(calls[1].url.searchParams.get('timezone'), 'Etc/UTC');
});
test('an ambiguous creation failure is surfaced without an automatic retry', async () => {
let calls = 0;
const client = createMavanClient({
apiKey: 'fixture-not-a-real-key',
baseUrl: 'https://mavan.example',
fetchImpl: async () => {
calls++;
return Response.json(
{ message: 'Fixture upstream failure' },
{ status: 503 },
);
},
});
await assert.rejects(
client.createStake({}, '00000000-0000-4000-8000-000000000000'),
(error) => error instanceof MavanApiError && error.status === 503,
);
assert.equal(calls, 1);
});scripts/ethereum-wallet.test.mjs
// Credential-free fixtures: no network requests, signing keys, or real broadcasts.
import assert from 'node:assert/strict';
import test from 'node:test';
import {
depositExpectations,
exitExpectations,
sendMavanTransaction,
} from './ethereum-wallet.mjs';
const owner = `0x${'11'.repeat(20)}`;
const pubkey = `0x${'22'.repeat(48)}`;
const config = {
chainId: 1,
pectraBatchDepositContractAddress: `0x${'33'.repeat(20)}`,
ethValidatorWithdrawalContractAddress:
'0x00000961Ef480Eb55e80D19ad83579A64c007002',
};
const gasBudget = { maxGasCostWei: 42_000n };
const input = {
withdrawalAddress: owner,
suggestedFeeRecipient: owner,
stakeAmountGwei: '32000000000',
};
const created = {
transaction: {},
stake: {
withdrawalAddress: owner,
validators: [
{
pubkey,
withdrawal_credentials: `0x02${'0'.repeat(22)}${owner.slice(2)}`,
suggestedFeeRecipient: owner,
signature: `0x${'44'.repeat(96)}`,
amount: input.stakeAmountGwei,
},
],
},
};
function feeRpc(fee = 1n, chainId = '0x1') {
return {
request: async ({ method, params }) => {
if (method === 'eth_chainId') return chainId;
assert.equal(method, 'eth_call');
assert.deepEqual(params, [
{
to: config.ethValidatorWithdrawalContractAddress.toLowerCase(),
data: '0x',
},
'latest',
]);
return `0x${fee.toString(16).padStart(64, '0')}`;
},
};
}
function wallet(chainId = '0x1') {
const calls = [];
return {
calls,
request: async (request) => {
calls.push(request);
if (request.method === 'eth_chainId') return chainId;
if (request.method === 'eth_requestAccounts') return [owner];
assert.equal(request.method, 'eth_sendTransaction');
return `0x${'55'.repeat(32)}`;
},
};
}
function transaction(expected) {
return {
chainId: expected.chainId,
to: expected.toAddress,
value: expected.valueWei.toString(),
data: expected.data,
gas: '21000',
maxFeePerGas: '2',
maxPriorityFeePerGas: '1',
analysis: { observations: [], simulations: {} },
};
}
const deposit = depositExpectations(created, input, config);
const exit = () =>
exitExpectations(pubkey, owner, config, {
rpc: feeRpc(),
maxExitRequestFeeWei: 10n,
});
test('fixture demo: validate a deposit and an independently quoted exit before mocked signing', async () => {
assert.equal(deposit.valueWei, 32_000_000_000_000_000_000n);
for (const expected of [deposit, await exit()]) {
const provider = wallet();
await sendMavanTransaction(
provider,
transaction(expected),
expected,
gasBudget,
);
assert.deepEqual(
provider.calls.map(({ method }) => method),
['eth_chainId', 'eth_requestAccounts', 'eth_sendTransaction'],
);
const sent = provider.calls.at(-1).params[0];
assert.equal(sent.value, `0x${expected.valueWei.toString(16)}`);
assert.equal(sent.data, expected.data);
assert.equal('nonce' in sent, false);
assert.equal('analysis' in sent, false);
}
});
test('a 1 ETH API exit fee cannot authorize itself; reject before any wallet request', async () => {
const expected = await exit();
const provider = wallet();
await assert.rejects(
sendMavanTransaction(
provider,
{ ...transaction(expected), value: '1000000000000000000' },
expected,
gasBudget,
),
/Transaction value mismatch/,
);
assert.deepEqual(provider.calls, []);
await assert.rejects(
exitExpectations(pubkey, owner, config, {
rpc: feeRpc(11n),
maxExitRequestFeeWei: 10n,
}),
/exceeds the approved maximum/,
);
});
test('both transaction types require a gas budget and reject total gas cost above it', async () => {
for (const expected of [deposit, await exit()]) {
const provider = wallet();
await assert.rejects(
sendMavanTransaction(provider, transaction(expected), expected),
/maximum gas cost/,
);
await assert.rejects(
sendMavanTransaction(provider, transaction(expected), expected, {
maxGasCostWei: 41_999n,
}),
/exceeds the approved budget/,
);
assert.deepEqual(provider.calls, []);
}
});
test('changed chain, destination, calldata and unsafe analysis stop before wallet access', async () => {
for (const [change, message] of [
[{ chainId: 2 }, /chain mismatch/],
[{ to: owner }, /destination mismatch/],
[{ data: '0x' }, /calldata mismatch/],
[
{ analysis: { observations: [{ severity: 'danger' }] } },
/analysis failure/,
],
[
{
analysis: {
observations: [],
simulations: { deposit: { success: false } },
},
},
/analysis failure/,
],
]) {
const provider = wallet();
await assert.rejects(
sendMavanTransaction(
provider,
{ ...transaction(deposit), ...change },
deposit,
gasBudget,
),
message,
);
assert.deepEqual(provider.calls, []);
}
});
test('wrong wallet network never requests accounts or broadcasts', async () => {
const provider = wallet('0x2');
await assert.rejects(
sendMavanTransaction(provider, transaction(deposit), deposit, gasBudget),
/Switch the wallet/,
);
assert.deepEqual(
provider.calls.map(({ method }) => method),
['eth_chainId'],
);
});
test('exit policy rejects absent limits, wrong RPC network and missing fee data', async () => {
await assert.rejects(
exitExpectations(pubkey, owner, config, { rpc: feeRpc() }),
/maximum exit request fee/,
);
await assert.rejects(
exitExpectations(pubkey, owner, config, {
rpc: feeRpc(1n, '0x2'),
maxExitRequestFeeWei: 10n,
}),
/Fee RPC chain mismatch/,
);
await assert.rejects(
exitExpectations(pubkey, owner, config, {
rpc: {
request: async ({ method }) =>
method === 'eth_chainId' ? '0x1' : '0x',
},
maxExitRequestFeeWei: 10n,
}),
/fee is unavailable/,
);
});Updated 25 days ago
