> ## Documentation Index
> Fetch the complete documentation index at: https://neardocs-update-rpc-openapi.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Your First Smart Contract

> Create your first smart contract in Rust and deploy it to the NEAR testnet.

export const Github = ({url, start, end, fname, language, withSourceLink = true}) => {
  const [code, setCode] = useState(null);
  function toRaw(ref) {
    const fullUrl = ref.slice(ref.indexOf('https'));
    const [url] = fullUrl.split('#');
    const [org, repo, , branch, ...pathSeg] = new URL(url).pathname.split('/').slice(1);
    return `https://raw.githubusercontent.com/${org}/${repo}/${branch}/${pathSeg.join('/')}`;
  }
  async function fetchCode(url, fromLine, toLine) {
    let res;
    if (typeof window !== 'undefined') {
      const validUntil = localStorage.getItem(`${url}-until`);
      if (validUntil && Number(validUntil) > Date.now()) {
        res = localStorage.getItem(url);
      }
    }
    if (!res) {
      try {
        res = await (await fetch(url)).text();
        if (typeof window !== 'undefined') {
          localStorage.setItem(url, res);
          localStorage.setItem(`${url}-until`, String(Date.now() + 60000));
        }
      } catch {
        return 'Error fetching code, please try reloading';
      }
    }
    let body = res.split('\n');
    const from = fromLine ? Number(fromLine) - 1 : 0;
    const to = toLine ? Number(toLine) : body.length;
    body = body.slice(from, to);
    const precedingSpace = body.reduce((prev, line) => {
      if (line.length === 0) return prev;
      const spaces = line.match(/^\s+/);
      if (spaces) return Math.min(prev, spaces[0].length);
      return 0;
    }, Infinity);
    return body.map(line => line.slice(precedingSpace === Infinity ? 0 : precedingSpace)).join('\n');
  }
  function buildSourceUrl(url, start, end) {
    const base = url.split('#')[0];
    if (start && end) return `${base}#L${start}-L${end}`;
    if (start) return `${base}#L${start}`;
    return base;
  }
  useEffect(() => {
    const rawUrl = toRaw(url);
    fetchCode(rawUrl, start, end).then(res => setCode(res));
  }, [url, start, end]);
  const sourceUrl = buildSourceUrl(url, start, end);
  const fileName = fname ?? sourceUrl.split('/').pop();
  return <div className="my-5">
      {code === null ? <div>Loading...</div> : <CodeBlock language={language} filename={fileName} lines>
          {code}
        </CodeBlock>}
      {withSourceLink && <div className="flex justify-end" style={{
    marginTop: "-1rem"
  }}>
          <a href={sourceUrl} target="_blank" rel="noreferrer noopener" className="text-[0.6875rem] font-medium text-[#656d76] no-underline hover:text-[#1f2328] dark:text-[#8b949e] dark:hover:text-[#e6edf3]">
            See code on GitHub
          </a>
        </div>}
    </div>;
};

Welcome! [NEAR accounts](../protocol/accounts-contracts/account-model) can store small apps known as smart contracts. In this tutorial, we'll guide you through creating your first contract on the NEAR **testnet**.

Create an auction contract that allows users to place bids, track the highest bidder, and claim tokens at the end of the auction.

<Accordion title="Prefer an online IDE?">
  Want to jump right into the code without setting up a local dev environment?

  Check out [NEAR Playground](https://nearplay.app/) for an easy-to-use online IDE with pre-configured templates.

  <img src="https://mintcdn.com/neardocs-update-rpc-openapi/DU4IGfk1CKPKKvuz/assets/docs/smart-contracts/NEAR-Playground.png?fit=max&auto=format&n=DU4IGfk1CKPKKvuz&q=85&s=d9ce39cbdd620c9ea4cfc6f12bc0039c" alt="NEAR Playground" width="1351" height="1078" data-path="assets/docs/smart-contracts/NEAR-Playground.png" />

  [![Build a Counter in NearPlay](https://img.shields.io/badge/Open%20in%20NearPlay-14b8a6?style=for-the-badge\&logo=data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9IndoaXRlIiBzdHJva2Utd2lkdGg9IjIiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCIgc3Ryb2tlLWxpbmVqb2luPSJyb3VuZCI+PHBhdGggZD0ibTE4IDcgNCA0LTQgNE00IDEybDQgNC00LTQgNC00Ii8+PC9zdmc+\&logoColor=white)](https://nearplay.app/embed/3450a8a0-57dc-4d3a-b5d0-7bed58a0c2a9)
</Accordion>

***

## Prerequisites

Before starting, make sure to set up your development environment.

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Install Rust: https://www.rust-lang.org/tools/install
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

# Contracts will be compiled to wasm, so we need to add the wasm target
rustup target add wasm32-unknown-unknown

# Install NEAR CLI-RS to deploy and interact with the contract
curl --proto '=https' --tlsv1.2 -LsSf https://github.com/near/near-cli-rs/releases/latest/download/near-cli-rs-installer.sh | sh

# Install cargo near to help building the contract
curl --proto '=https' --tlsv1.2 -LsSf https://github.com/near/cargo-near/releases/latest/download/cargo-near-installer.sh | sh
```

***

## Creating the contract

Create a smart contract with the `cargo near` scaffolding tool by following its instructions:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Create a new contract called "auction"
cargo near new auction
```

<img src="https://mintcdn.com/neardocs-update-rpc-openapi/DU4IGfk1CKPKKvuz/assets/docs/smart-contracts/hello-near-rs.gif?s=a14a965e0a48df4ad11cbdd8a5884c4a" alt="img" width="1702" height="1120" data-path="assets/docs/smart-contracts/hello-near-rs.gif" />

*Creating a project using `cargo near new`*

<Tip>
  For this tutorial, we chose to name the project `auction`, but feel free to use any name you prefer.
</Tip>

***

## Build and deploy the contract

Let's build the contract, create a NEAR testnet account, and deploy the contract to it.

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Run the sandbox tests to verify the contract works as expected
cargo test

# Build the contract
cargo near build non-reproducible-wasm

# Create a free testnet account, replace `<account.testnet>` with your desired account name
near create-account <account.testnet> --useFaucet

# Deploy the contract to the account
near deploy <account.testnet> ./target/near/auction.wasm
```

<Tip>
  **Already have a testnet account?**

  If you already have a `testnet` account and would like to use it instead, you can log in with the command `near login`.
</Tip>

<Accordion title="Got an error on Windows?">
  When working in `WSL`—or another headless Linux environment—you might encounter issues creating an account because the CLI tries to save keys to the system keychain.

  In such cases, you can try the following command to create the account:

  ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
  near account create-account sponsor-by-faucet-service <your-account-id.testnet> autogenerate-new-keypair save-to-legacy-keychain network-config testnet create
  ```
</Accordion>

**Congrats!** Your contract now lives in the NEAR testnet network.

***

## Initialize the auction

The contract stores the highest bid, auction end time, auctioneer address, and a flag to track whether proceeds have been claimed. Its `init` function sets these values when the contract is first initialized:

<Github fname="lib.rs" language="rust" url="https://github.com/near-examples/auctions-tutorial/blob/main/contract-rs/01-basic-auction/src/lib.rs" start="7" end="35" />

Initialize the auction by setting its end time and designating the auctioneer to receive the funds:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Get a timestamp for 5 minutes from now (in nanoseconds)
FIVE_MINUTES_FROM_NOW=$(( $(date +%s%N) + 5 * 60 * 1000000000 ))

# Initialize the auction
near call <account.testnet> init "{\"end_time\": \"$FIVE_MINUTES_FROM_NOW\", \"auctioneer\": \"influencer.testnet\"}" --useAccount <account.testnet>
```

<Tip>
  Feel free to replace `influencer.testnet` with any valid testnet account—this is where the winning bid will be sent.
</Tip>

## Place and view bids

Place a bid in the auction by calling the `bid` method and attaching a NEAR deposit. The function checks whether the auction is ongoing and whether the bid is higher than the stored amount. If it is, the contract records the new bid and refunds the previous bidder.

<Github fname="lib.rs" language="rust" url="https://github.com/near-examples/auctions-tutorial/blob/main/contract-rs/01-basic-auction/src/lib.rs" start="37" end="64" />

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Create a new account to place the bid
near create-account <bidder-account.testnet> --useFaucet

# Place a bid of 0.01 NEAR
near call <account.testnet> bid '{}' --deposit 0.01  --useAccount <bidder-account.testnet>
```

<Note>
  In this example, use the `<bidder-account.testnet>` account (remember to rename it) to call the `bid` function and attach a deposit of `0.01` NEAR.
</Note>

### View the highest bid

The `get_highest_bid` function only reads from the contract state, so it does not require a transaction or signature. You can also use the contract's other view methods to query the auction end time, auctioneer, and claim status:

<Github fname="lib.rs" language="rust" url="https://github.com/near-examples/auctions-tutorial/blob/main/contract-rs/01-basic-auction/src/lib.rs" start="78" end="92" />

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
near view <account.testnet> get_highest_bid '{}'
```

<Accordion title="Expected Output">
  ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
  {
    "bidder": "<bidder-account.testnet>",
    "amount": "10000000000000000000000"
  }
  ```
</Accordion>

The amount is shown in `yoctoNEAR`, the smallest unit of NEAR. Since 1 NEAR equals `10^24` yoctoNEAR, the displayed amount is `0.01` NEAR.

<Tip>
  Feel free to create more bidder accounts and place bids to see how the highest bid changes.
</Tip>

## Claim the proceeds

After the auction ends, anyone can call the `claim` method. It transfers the amount of the highest bid to the auctioneer and ends the auction:

<Github fname="lib.rs" language="rust" url="https://github.com/near-examples/auctions-tutorial/blob/main/contract-rs/01-basic-auction/src/lib.rs" start="65" end="76" />

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
near call <account.testnet> claim '{}' --useAccount <account.testnet>
```

<Info>
  **Who won?**

  After the auction ends, you can determine the highest bidder by calling the `get_highest_bid` method again.
</Info>

***

## Frequently Asked Questions

<AccordionGroup>
  <Accordion title="What about mainnet?">
    You can deploy a contract to mainnet using the same commands. Create a mainnet account and use the `--networkId mainnet` flag in the `near` CLI commands.
  </Accordion>

  <Accordion title="How much does it cost to deploy?">
    The cost of deploying a contract depends on its size: approximately 1 Ⓝ per 100 KB.
  </Accordion>

  <Accordion title="Can I update a contract after deploying?">
    Yes. Redeploy with `near deploy <account> <wasm-file>`. The account stays the same, and the code is updated.
  </Accordion>

  <Accordion title="How do I test without deploying?">
    Use the sandbox tests shown in this guide. They run locally in a simulated NEAR environment.
  </Accordion>

  <Accordion title="Can I use a language other than Rust?">
    Yes. You can write smart contracts in any language that compiles to WebAssembly. Our documentation focuses on Rust, but community-maintained SDKs are available for other languages. See [supported languages](/smart-contracts/what-is#supported-languages).
  </Accordion>
</AccordionGroup>

***

## Moving forward

<CardGroup cols={3}>
  <Card title="Create a Frontend" href="../web3-apps/tutorials/mastering-near/2.1-frontend">
    Check the auction frontend tutorial to learn how to build a simple web app that interacts with the auction contract.
  </Card>

  <Card title="Extend the Contract" href="../web3-apps/tutorials/mastering-near/3.1-nft">
    Follow the auction NFT tutorial to award the highest bidder a Non-Fungible Token (NFT) and allow users to bid using Fungible Tokens (FT).
  </Card>

  <Card title="Learn More about the SDK" href="./anatomy/anatomy">
    Check our Anatomy of a Contract page to understand the different components that make up a NEAR smart contract.
  </Card>
</CardGroup>

<br />

<Accordion title="Versioning for this article">
  At the time of this writing, this example works with the following versions:

  * rustc: `1.86.0`
  * near-cli-rs: `0.22.0`
  * cargo-near: `0.16.1`
</Accordion>
