> ## Documentation Index
> Fetch the complete documentation index at: https://docs.near.org/llms.txt
> Use this file to discover all available pages before exploring further.

# Global Contracts

> Learn how to deploy a Global contract and use it from another account.

export const Github = ({url, start, end, fname, 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 startLine = start ? Number(start) : 1;
  const fileName = fname ?? sourceUrl.split('/').pop();
  return <div className="rounded-[0.625rem] border border-[#d0d7de] dark:border-[#30363d] overflow-hidden my-5 text-[0.8125rem] font-mono shadow-sm dark:shadow-[0_4px_24px_rgba(0,0,0,0.18)]">

      {}
      <div className="flex items-center justify-between py-2 px-[0.875rem] bg-[#f6f8fa] dark:bg-[#161b22] border-b border-[#d0d7de] dark:border-[#30363d]">
        <div className="flex items-center gap-2 text-[#656d76] dark:text-[#8b949e]">
          <svg width="15" height="15" viewBox="0 0 24 24" fill="currentColor">
            <path d="M12 0C5.37 0 0 5.37 0 12c0 5.31 3.435 9.795 8.205 11.385.6.105.825-.255.825-.57 0-.285-.015-1.23-.015-2.235-3.015.555-3.795-.735-4.035-1.41-.135-.345-.72-1.41-1.23-1.695-.42-.225-1.02-.78-.015-.795.945-.015 1.62.87 1.845 1.23 1.08 1.815 2.805 1.305 3.495.99.105-.78.42-1.305.765-1.605-2.67-.3-5.46-1.335-5.46-5.925 0-1.305.465-2.385 1.23-3.225-.12-.3-.54-1.53.12-3.18 0 0 1.005-.315 3.3 1.23.96-.27 1.98-.405 3-.405s2.04.135 3 .405c2.295-1.56 3.3-1.23 3.3-1.23.66 1.65.24 2.88.12 3.18.765.84 1.23 1.905 1.23 3.225 0 4.605-2.805 5.625-5.475 5.925.435.375.81 1.095.81 2.22 0 1.605-.015 2.895-.015 3.3 0 .315.225.69.825.57A12.02 12.02 0 0 0 24 12c0-6.63-5.37-12-12-12z" />
          </svg>
          <span className="text-xs font-medium text-[#1f2328] dark:text-[#e6edf3]">
            {fileName}
          </span>
        </div>
        {start && end && <span className="text-[0.6875rem] text-[#656d76] dark:text-[#8b949e] bg-[#eaeef2] dark:bg-[#21262d] border border-[#d0d7de] dark:border-[#30363d] rounded-full py-0.5 px-2">
            Lines {start}–{end}
          </span>}
      </div>

      {}
      <div className="overflow-auto max-h-[480px] bg-white dark:bg-[#0d1117] [&_tr]:border-b-0 [&_td]:border-b-0">
        {code === null ? <div className="py-5 px-4 text-xs text-[#656d76] dark:text-[#6e7681]">
            Loading...
          </div> : <table className="w-full border-collapse leading-[1.6]">
            <tbody>
              {code.split('\n').map((line, i) => <tr key={i} className="align-top border-0">
                  <td style={{
    minWidth: '60px'
  }} className="select-none pl-2 pr-3 text-right text-[0.7rem] text-[#8c959f] dark:text-[#3d444d] w-[1%] whitespace-nowrap border-r border-0 border-r-[#d0d7de] dark:border-r-[#21262d]">
                    {startLine + i}
                  </td>
                  <td className="pl-4 pr-6 text-[0.8125rem] text-[#1f2328] dark:text-[#e6edf3] whitespace-pre">
                    {line || ' '}
                  </td>
                </tr>)}
            </tbody>
          </table>}
      </div>

      {}
      {withSourceLink && <div className="flex justify-end py-1.5 px-[0.875rem] bg-[#f6f8fa] dark:bg-[#161b22] border-t border-[#d0d7de] dark:border-[#21262d]">
          <a href={sourceUrl} target="_blank" rel="noreferrer noopener" className="text-[0.6875rem] font-medium text-[#656d76] dark:text-[#8b949e] no-underline flex items-center gap-[0.3rem] hover:text-[#1f2328] dark:hover:text-[#e6edf3] transition-colors">
            View on GitHub
            <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
              <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6" />
              <polyline points="15 3 21 3 21 9" />
              <line x1="10" y1="14" x2="21" y2="3" />
            </svg>
          </a>
        </div>}
    </div>;
};

If you've ever deployed the same contract code to multiple accounts, you’ve likely noticed that each deployment requires you to pay the full storage cost again.

Imagine that you want to deploy the same 500 KB contract to three accounts: each deployment pays 5 NEAR for the storage — a total of 15 NEAR is locked just to hold identical code.
[Global Contracts](/smart-contracts/global-contracts) eliminates this redundancy by allowing the same contract code to be shared across multiple accounts, so storage cost is paid only once.

In this tutorial you'll learn how to deploy and use a [global contract by Account ID](#global-contract-by-account-id) or [by Hash](#global-contract-by-hash), depending on your needs.

<Info>
  **Global Contract types**

  * [By Account](/smart-contracts/global-contracts#reference-by-account): an upgradable contract is published globally under a specific account ID.
  * [By Hash](/smart-contracts/global-contracts#reference-by-hash): an immutable contract is deployed globally and identified by its code hash.
</Info>

## Examples

Let's define two example smart contracts that we can deploy using Global Contracts, and evaluate which alternative (by Account ID or by Hash) is the best for each case.

* **DAO Factory**: A tool that allows any user to deploy their own DAO governance instance.
* **NFT Collection Factory**: A service that lets users create their own NFT contracts with fixed metadata and royalty values.

<Tip>
  **Do you need a Global Contract?**
  Not sure if you need a Global Contract? Check these questions to decide [when to use a global contract](/smart-contracts/global-contracts#when-to-use-global-contracts).
</Tip>

### Global Contract by Account ID

For example, let's consider the **DAO Factory** case.

Since the same contract is deployed many times by end users across different accounts, this clearly meets the threshold where [Global Contracts](/smart-contracts/global-contracts) become financially efficient. Also, since upgradeability may be useful down the line (e.g., to patch bugs or extend functionality), it's a great case to use a [Global Contract by Account ID](/smart-contracts/global-contracts#reference-by-account).

### Global Contract by Hash

Now let's take for example the **NFT Collection Factory** case.

Since each user deploys the same contract, but once deployed, it should never change (security and immutability are critical), this makes a perfect case to use a [Global Contract by Hash](/smart-contracts/global-contracts#reference-by-hash).

## Deploying a Global Contract

Next, let's see how you can deploy a global contract by Account ID (for the DAO Factory), or by Hash (for the NFT Collection Factory).
As stated, Global contracts can be deployed in 2 ways:

* by their [hash](/smart-contracts/global-contracts#reference-by-hash).
* by the owner [account ID](/smart-contracts/global-contracts#reference-by-account).

Contracts deployed by hash are effectively immutable and cannot be updated.
When deployed by account ID the owner can redeploy the contract updating it for all its users.

<Info>
  Note that deploying a global contract incurs high storage costs. Tokens are burned to compensate for storing the contract on-chain, unlike regular contracts where tokens are locked based on contract size.
</Info>

### Deployment

Global contracts can be deployed using [`NEAR CLI`](/tools/cli) or by code using [NEAR APIs](/tools/near-api#deploy-a-global-contract) (JavaScript and Rust).

Since there are two ways to reference a global contract ([by account](/smart-contracts/global-contracts#reference-by-account) or [by hash](/smart-contracts/global-contracts#reference-by-hash)), the deployment step depends on the type of global contract that you want to store on the blockchain.

<Tabs>
  <Tab title="🖥️ CLI">
    The process is similar to [deploying a regular contract](/smart-contracts/release/deploy#deploying-the-contract) but `deploy-as-global` command should be used instead of `deploy`.

    <Tabs>
      <Tab title="By Account ID">
        To deploy a global contract by account, you need to use `as-global-account-id` and pass the source `<account_Id>` where the contract will be deployed.

        ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
        near contract deploy-as-global use-file <route_to_wasm> as-global-account-id <account_id> network-config testnet sign-with-keychain send
        ```
      </Tab>

      <Tab title="By Hash">
        To deploy a global contract by hash, you need to use `as-global-hash` function and pass the source `<account_Id>` to fund the transaction.

        ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
        near contract deploy-as-global use-file <route_to_wasm> as-global-hash <account_id> network-config testnet sign-with-keychain send
        ```
      </Tab>
    </Tabs>
  </Tab>

  <Tab title="🌐 JavaScript">
    Once you've created an Account instance, you can deploy your regular contract as a global contract.

    <Tabs>
      <Tab title="By Account ID">
        Let’s look at an example of deploying a global contract by account.

        To do this, use the `deployGlobalContract` function and set the mode to `accountId`, along with the contract’s code bytes.

        <Github fname="deploy-global-contract-by-account.ts" language="js" url="https://github.com/near-examples/near-api-examples/blob/main/near-api-js/examples/deploy-global-contract-by-account.ts#L22-L27" start="22" end="27" />
      </Tab>

      <Tab title="By Hash">
        Let’s look at an example of deploying a global contract by hash.

        To do this, use the `deployGlobalContract` function and set the mode to `codeHash`, along with the contract’s code bytes.

        <Github fname="deploy-global-contract-by-hash.ts" language="js" url="https://github.com/near-examples/near-api-examples/blob/main/near-api-js/examples/deploy-global-contract-by-hash.ts#L24-L29" start="24" end="29" />
      </Tab>
    </Tabs>
  </Tab>

  <Tab title="🦀 Rust">
    Once you've created an Account instance, you can deploy your regular contract as a global contract.

    <Tabs>
      <Tab title="By Account ID">
        Let’s look at an example of deploying a global contract by account.

        To do this, use the `deploy_global_contract_code` function and use the method `as_account_id`, along with the contract’s code bytes.

        <Github fname="global_contract_accountid.rs" language="rust" url="https://github.com/near-examples/near-api-examples/blob/main/rust/examples/global_contract_accountid.rs#L17-L28" start="17" end="28" />
      </Tab>

      <Tab title="By Hash">
        Let’s look at an example of deploying a global contract by hash.

        To do this, use the `deploy_global_contract_code` function and use the method `as_hash`, along with the contract’s code bytes.

        <Github fname="global_contract_hash.rs" language="rust" url="https://github.com/near-examples/near-api-examples/blob/main/rust/examples/global_contract_hash.rs#L17-L28" start="17" end="28" />
      </Tab>
    </Tabs>
  </Tab>
</Tabs>

<Tip>
  Check the [NEAR API reference documentation](/tools/near-api#deploy-a-global-contract) for complete code examples.
</Tip>

### Usage

Once a [global contract](/smart-contracts/global-contracts) has been [deployed](#deployment), it can be attached to any NEAR account using [`NEAR CLI`](/tools/cli) or by code using [NEAR APIs](/tools/near-api#use-a-global-contract) (JavaScript and Rust).

Let’s see how you can reference and use your global contract from another account.

<Tabs>
  <Tab title="🖥️ CLI">
    Use `near deploy` command. Such a contract behaves exactly like a regular contract.

    <Tabs>
      <Tab title="By Account ID">
        To reference a global contract by account, you need to call the `useGlobalContract` function and pass the source `accountId` where the contract was originally deployed.

        ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
        # Using global contract deployed by <global_contract_account_id> account id
        near contract deploy <account_id> use-global-account-id <global_contract_account_id> without-init-call network-config testnet
        ```
      </Tab>

      <Tab title="By Hash">
        To reference a global contract by hash, you need to call the `useGlobalContract` function and pass the source `codeHash` of the original contract.

        ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
        # Using global contract deployed by <global_contract_hash> hash
        near contract deploy <account_id> use-global-hash <global_contract_hash> without-init-call network-config testnet
        ```
      </Tab>
    </Tabs>
  </Tab>

  <Tab title="🌐 JavaScript">
    <Tabs>
      <Tab title="By Account ID">
        To reference a global contract by account, you need to call the `useGlobalContract` function and pass the source `accountId` where the contract was originally deployed.

        <Github fname="deploy-global-contract-by-account.ts" language="js" url="https://github.com/near-examples/near-api-examples/blob/main/near-api-js/examples/deploy-global-contract-by-account.ts#L39-L45" start="39" end="45" />
      </Tab>

      <Tab title="By Hash">
        To reference a global contract by hash, you need to call the `useGlobalContract` function and pass the source `codeHash` of the original contract.

        ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
        const hash = bs58.encode(sha256(wasm));
        ```

        <Github fname="deploy-global-contract-by-hash.ts" language="js" url="https://github.com/near-examples/near-api-examples/blob/main/near-api-js/examples/deploy-global-contract-by-hash.ts#L45-L53" start="45" end="53" />
      </Tab>
    </Tabs>
  </Tab>

  <Tab title="🦀 Rust">
    <Tabs>
      <Tab title="By Account ID">
        To reference a global contract by account, you need to call the `use_global_account_id` function and pass the source `accountId` where the contract was originally deployed.

        <Github fname="global_contract_accountid.rs" language="rust" url="https://github.com/near-examples/near-api-examples/blob/main/rust/examples/global_contract_accountid.rs#L61-L70" start="61" end="70" />
      </Tab>

      <Tab title="By Hash">
        To reference a global contract by hash, you need to call the `use_global_hash` function and pass the source `hash` of the original contract.

        ```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
          // Get a global contract hash
          let code = std::fs::read("../contracts/contract.wasm").unwrap();
          let global_hash = near_primitives::hash::CryptoHash::hash_bytes(&code);
        ```

        <Github fname="global_contract_hash.rs" language="rust" url="https://github.com/near-examples/near-api-examples/blob/main/rust/examples/global_contract_hash.rs#L62-L70" start="62" end="70" />
      </Tab>
    </Tabs>
  </Tab>
</Tabs>

<Tip>
  Check the [NEAR API reference documentation](/tools/near-api#use-a-global-contract) for complete code examples.
</Tip>
