> For the complete documentation index, see [llms.txt](https://docs.validationcloud.io/staking/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.validationcloud.io/staking/ethereum/staking-tutorial/api/full-code.md).

# Full Code

```javascript
const auth0 = require('auth0');
const ethers = require('ethers');

const STAKING_BASE_API_URL = 'https://ethereum-staking.sprd.validationcloud.io/v1/api';
const STAKING_REQUEST_URL = `${STAKING_BASE_API_URL}/ethereum/mainnet/stake_transaction`;
const STAKING_BROADCAST_TX_URL = `${STAKING_BASE_API_URL}/ethereum/mainnet/broadcast_transaction`;
const AUTH0_DOMAIN = 'validationcloud.us.auth0.com';

async function getAuth0Credentials() {
  const clientId = process.env.CLIENT_ID;
  if (!clientId) {
    throw 'CLIENT_ID environment variable must be defined';
  }

  const clientSecret = process.env.CLIENT_SECRET;
  if (!clientSecret) {
    throw 'CLIENT_SECRET environment variable must be defined';
  }

  return { clientId, clientSecret };
}

async function getToken() {
  const { clientId, clientSecret } = await getAuth0Credentials();

  const authClient = new auth0.AuthenticationClient({
    domain: AUTH0_DOMAIN,
    clientId: clientId,
    clientSecret: clientSecret,
  });

  const { data: tokens } = await authClient.oauth.clientCredentialsGrant({
    audience: 'staking',
  });

  return tokens.access_token;
}

async function createStakeTransaction(token, walletAddress, num) {
  const jsonBody = JSON.stringify({
    num_validators: num,
    wallet_address: walletAddress,
  });

  const response = await fetch(STAKING_REQUEST_URL, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
    body: jsonBody,
  });

  return await response.json();
}

async function broadcastStakingTransaction(token, signedTx) {
  const jsonBody = JSON.stringify({
    signed_transaction: signedTx,
  });

  const response = await fetch(STAKING_BROADCAST_TX_URL, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${token}`,
      'Content-Type': 'application/json',
    },
    body: jsonBody,
  });

  return await response.json();
}

function getWallet() {
  const privateKey = process.env.PRIVATE_KEY;
  if (!privateKey) {
    throw 'PRIVATE_KEY environment variable must be defined';
  }

  return new ethers.Wallet(privateKey);
}

async function signTransaction(wallet, transaction) {
  console.log(transaction);
  return await wallet.signTransaction({
    type: 0,
    to: transaction.to,
    from: wallet.address,
    nonce: transaction.nonce,
    gasLimit: transaction.gas,
    gasPrice: transaction.gas_price,
    data: transaction.data,
    value: transaction.value,
    chainId: ethers.toBeHex(transaction.chain_id),
  });
}

async function stakeValidators(num) {
  const authToken = await getToken();
  const wallet = getWallet();
  const stakeRequest = await createStakeTransaction(authToken, wallet.address, num);
  const signedTx = await signTransaction(wallet, stakeRequest.transaction);
  const broadcastTxResponse = await broadcastStakingTransaction(authToken, signedTx);
  console.log(broadcastTxResponse);
}

const NUM_OF_VALIDATORS = 1;

stakeValidators(NUM_OF_VALIDATORS)
  .then(() => {
    console.log('Staking successful');
  })
  .catch(error => {
    console.log('Failed to stake with error');
    console.log(error);
  });
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.validationcloud.io/staking/ethereum/staking-tutorial/api/full-code.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
