> ## 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.

# Transfers & Actions

> Learn how contracts can make transfers, call other contracts, and more

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>;
};

This page describes the different types of actions that a smart contract can perform on NEAR like transferring NEAR, calling other contracts, creating sub-accounts, and deploying contracts. It also explains how to add access keys to accounts.

Smart contracts can perform specific `Actions` such as transferring NEAR, or calling other contracts.

An important property of `Actions` is that they can be batched together when acting on the same contract. **Batched actions** act as a unit: they execute in the same [receipt](/protocol/transactions/transaction-execution#receipts--finality), and if **any fails**, then they **all get reverted**.

<Info>
  `Actions` can be batched only when they act on the **same contract**. You can batch calling two methods on a contract,
  but **cannot** call two methods on different contracts.
</Info>

***

## Transfer NEAR Ⓝ

You can send `$NEAR` from your contract to any other account on the network. The Gas cost for transferring `$NEAR` is fixed and is based on the protocol's genesis config. Currently, it costs `~0.45 TGas`.

<Tabs>
  <Tab title="🦀 Rust">
    ```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
      use near_sdk::{near, AccountId, Promise, NearToken};

      #[near(contract_state)]
      #[derive(Default)]
      pub struct Contract { }

      #[near]
      impl Contract {
        pub fn transfer(&self, to: AccountId, amount: NearToken){
          Promise::new(to).transfer(amount);
        }
      }
    ```
  </Tab>

  <Tab title="🌐 JavaScript">
    ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
      import { NearBindgen, NearPromise, call } from 'near-sdk-js'
      import { AccountId } from 'near-sdk-js/lib/types'

      @NearBindgen({})
      class Contract{
        @call({})
        transfer({ to, amount }: { to: AccountId, amount: bigint }) {
          return NearPromise.new(to).transfer(amount);
        }
      }
    ```
  </Tab>

  <Tab title="🐍 Python">
    ```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
    from near_sdk_py import call, Contract
    from near_sdk_py.promises import Promise

    class ExampleContract(Contract):
        @call
        def transfer(self, to, amount):
            """Transfers NEAR to another account"""
            # Create a promise to transfer NEAR
            return Promise.create_batch(to).transfer(amount)
    ```
  </Tab>

  <Tab title="🐹 GO">
    <Github fname="main.go" language="go" url="https://github.com/Emir-Asanov/near-go-examples/blob/example-release-1/actions/main.go" start="20" end="36" />
  </Tab>
</Tabs>

<Tip>
  **Why is there no callback?**
  The only case where a transfer will fail is if the receiver account does **not** exist.
</Tip>

<Warning>
  Remember that your balance is used to cover for the contract's storage. When sending money, make sure you always leave enough to cover for future storage needs.
</Warning>

***

## Function Call

Your smart contract can call methods in another contract. In the snippet below we call a method
in a deployed [Hello NEAR](../quickstart) contract, and check if everything went
right in the callback.

<Tabs>
  <Tab title="🦀 Rust">
    ```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
      use near_sdk::{near, env, log, Promise, Gas, PromiseError};
      use serde_json::json;

      #[near(contract_state)]
      #[derive(Default)]
      pub struct Contract { }

      const HELLO_NEAR: &str = "hello-nearverse.testnet";
      const NO_DEPOSIT: u128 = 0;
      const CALL_GAS: Gas = Gas(5_000_000_000_000);

      #[near]
      impl Contract {
        pub fn call_method(&self){
          let args = json!({ "message": "howdy".to_string() })
                    .to_string().into_bytes().to_vec();

          Promise::new(HELLO_NEAR.parse().unwrap())
          .function_call("set_greeting".to_string(), args, NO_DEPOSIT, CALL_GAS)
          .then(
            Promise::new(env::current_account_id())
            .function_call("callback".to_string(), Vec::new(), NO_DEPOSIT, CALL_GAS)
          );
        }

        pub fn callback(&self, #[callback_result] result: Result<(), PromiseError>){
          if result.is_err(){
              log!("Something went wrong")
          }else{
              log!("Message changed")
          }
        }
      }
    ```
  </Tab>

  <Tab title="🌐 JavaScript">
    ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
      import { NearBindgen, near, call, bytes, NearPromise } from 'near-sdk-js'
      import { AccountId } from 'near-sdk-js/lib/types'

      const HELLO_NEAR: AccountId = "hello-nearverse.testnet";
      const NO_DEPOSIT: bigint = BigInt(0);
      const CALL_GAS: bigint = BigInt("10000000000000");

      @NearBindgen({})
      class Contract {
        @call({})
        call_method({}): NearPromise {
          const args = bytes(JSON.stringify({ message: "howdy" }))

          return NearPromise.new(HELLO_NEAR)
          .functionCall("set_greeting", args, NO_DEPOSIT, CALL_GAS)
          .then(
            NearPromise.new(near.currentAccountId())
            .functionCall("callback", bytes(JSON.stringify({})), NO_DEPOSIT, CALL_GAS)
          )
          .asReturn()
        }

        @call({privateFunction: true})
        callback({}): boolean {
          let result, success;

          try{ result = near.promiseResult(0); success = true }
          catch{ result = undefined; success = false }

          if (success) {
            near.log(`Success!`)
            return true
          } else {
            near.log("Promise failed...")
            return false
          }
        }
      }
    ```
  </Tab>

  <Tab title="🐍 Python">
    ```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
    from near_sdk_py import call, callback, Contract
    from near_sdk_py.promises import CrossContract, Promise, PromiseResult
    from near_sdk_py.constants import ONE_TGAS

    # Constants
    HELLO_NEAR = "hello-nearverse.testnet"
    NO_DEPOSIT = 0
    CALL_GAS = 10 * ONE_TGAS

    class ExampleContract(Contract):
        @call
        def call_method(self):
            """Call a method on an external contract with a callback"""
            # Create a contract reference
            hello = CrossContract(HELLO_NEAR)
            
            # Call the external contract and use our callback to process the result
            return hello.call("set_greeting", {"message": "howdy"}).then("callback")
        
        @callback
        def callback(self, result: PromiseResult):
            """Handle the result of the external contract call"""
            # The @callback decorator automatically handles success/failure checking
            if not result.success:
                # The remote call failed
                self.log_error("Promise failed...")
                return False
            
            # The remote call succeeded
            self.log_info("Success!")
            return True
    ```
  </Tab>

  <Tab title="🐹 GO">
    <Github fname="main.go" language="go" url="https://github.com/Emir-Asanov/near-go-examples/blob/example-release-1/actions/main.go" start="40" end="73" />
  </Tab>
</Tabs>

<Warning>
  The snippet showed above is a low level way of calling other methods. We recommend make calls to other contracts as explained in the [Cross-contract Calls section](/smart-contracts/anatomy/crosscontract).
</Warning>

***

## Create a Sub Account

Your contract can create direct sub accounts of itself, for example, `user.near` can create `sub.user.near`.

Accounts do **NOT** have control over their sub-accounts, since they have their own keys.

Sub-accounts are simply useful for organizing your accounts (e.g. `dao.project.near`, `token.project.near`).

<Tabs>
  <Tab title="🦀 Rust">
    ```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
      use near_sdk::{near, env, Promise, NearToken};

      #[near(contract_state)]
      #[derive(Default)]
      pub struct Contract { }

      const MIN_STORAGE: NearToken = NearToken::from_millinear(1); //0.001Ⓝ

      #[near]
      impl Contract {
        pub fn create(&mut self, prefix: String) {
          let account_id = prefix + "." + &env::current_account_id().to_string();
          Promise::new(account_id.parse().unwrap())
            .create_account()
            .transfer(MIN_STORAGE);
        }
      }
    ```
  </Tab>

  <Tab title="🌐 JavaScript">
    ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
      import { NearBindgen, near, call, NearPromise } from 'near-sdk-js'

      const MIN_STORAGE: bigint = BigInt("1000000000000000000000") // 0.001Ⓝ

      @NearBindgen({})
      class Contract {
        @call({payableFunction:true})
        create({prefix}:{prefix: String}) {
          const account_id = `${prefix}.${near.currentAccountId()}`

          NearPromise.new(account_id)
          .createAccount()
          .transfer(MIN_STORAGE)
        }
      }
    ```
  </Tab>

  <Tab title="🐍 Python">
    ```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
    from near_sdk_py import call, Contract
    from near_sdk_py.promises import Promise
    from near_sdk_py.constants import ONE_NEAR

    # Minimum amount needed for storage
    MIN_STORAGE = ONE_NEAR // 1000  # 0.001Ⓝ

    class ExampleContract(Contract):
        @call
        def create(self, prefix):
            """Create a subaccount"""
            # Generate the new account ID
            account_id = f"{prefix}.{self.current_account_id}"
            
            # Create the new account and transfer some NEAR for storage
            return Promise.create_batch(account_id)\
                .create_account()\
                .transfer(MIN_STORAGE)
    ```
  </Tab>

  <Tab title="🐹 GO">
    <Github fname="main.go" language="go" url="https://github.com/Emir-Asanov/near-go-examples/blob/example-release-1/actions/main.go" start="77" end="94" />
  </Tab>
</Tabs>

<Tip>
  Notice that in the snippet we are transferring some money to the new account for storage
</Tip>

<Warning>
  When you create an account from within a contract, it has no keys by default. If you don't explicitly [add keys](#add-keys) to it or [deploy a contract](#deploy-a-contract) on creation then it will be [locked](../../protocol/accounts-contracts/access-keys#locked-accounts).
</Warning>

<hr className="subsection" />

#### Creating `.testnet` / `.near` Accounts

Accounts can only create immediate sub-accounts of themselves.

If your contract wants to create a `.mainnet` or `.testnet` account, then it needs to [call](#function-call)
the `create_account` method of `near` or `testnet` root contracts.

<Tabs>
  <Tab title="🦀 Rust">
    ```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
      use near_sdk::{near, Promise, Gas, NearToken };
      use serde_json::json;

      #[near(contract_state)]
      #[derive(Default)]
      pub struct Contract { }

      const CALL_GAS: Gas = Gas::from_gas(28_000_000_000_000);
      const MIN_STORAGE: NearToken = NearToken::from_yoctonear(1_820_000_000_000_000_000_000); //0.00182Ⓝ

      #[near]
      impl Contract {
        pub fn create_account(&mut self, account_id: String, public_key: String){
          let args = json!({
                      "new_account_id": account_id,
                      "new_public_key": public_key,
                    }).to_string().into_bytes().to_vec();

          // Use "near" to create mainnet accounts
          Promise::new("testnet".parse().unwrap())
            .function_call("create_account".to_string(), args, MIN_STORAGE, CALL_GAS);
        }
      }
    ```
  </Tab>

  <Tab title="🌐 JavaScript">
    ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
      import { NearBindgen, near, call, bytes, NearPromise } from 'near-sdk-js'

      const MIN_STORAGE: bigint = BigInt("1820000000000000000000"); //0.00182Ⓝ
      const CALL_GAS: bigint = BigInt("28000000000000");

      @NearBindgen({})
      class Contract {
        @call({})
        create_account({account_id, public_key}:{account_id: String, public_key: String}) {
          const args = bytes(JSON.stringify({
            "new_account_id": account_id,
            "new_public_key": public_key
          }))

          NearPromise.new("testnet")
          .functionCall("create_account", args, MIN_STORAGE, CALL_GAS);
        }
      }
    ```
  </Tab>

  <Tab title="🐍 Python">
    ```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
    from near_sdk_py import call, Contract
    from near_sdk_py.promises import Promise
    from near_sdk_py.constants import ONE_NEAR, ONE_TGAS

    # Constants
    MIN_STORAGE = int(1.82 * ONE_NEAR / 1000)  # 0.00182Ⓝ
    CALL_GAS = 28 * ONE_TGAS

    class ExampleContract(Contract):
        @call
        def create_account(self, account_id, public_key):
            """Create a testnet account by calling the testnet contract"""
            # Create the arguments for the create_account method
            args = {
                "new_account_id": account_id,
                "new_public_key": public_key
            }
            
            # Call the testnet contract to create the account
            return Promise.create_batch("testnet")\
                .function_call(
                    "create_account",
                    args,
                    MIN_STORAGE,
                    CALL_GAS
                )
    ```
  </Tab>

  <Tab title="🐹 GO">
    <Github fname="main.go" language="go" url="https://github.com/Emir-Asanov/near-go-examples/blob/example-release-1/actions/main.go" start="98" end="115" />
  </Tab>
</Tabs>

***

## Deploy a Contract

When creating an account you can also batch the action of deploying a contract to it. Note that for this, you will need to pre-load the byte-code you want to deploy in your contract.

<Tabs>
  <Tab title="🦀 Rust">
    ```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
      use near_sdk::{near, env, Promise, NearToken};

      #[near(contract_state)]
      #[derive(Default)]
      pub struct Contract { }

      const MIN_STORAGE: NearToken = NearToken::from_millinear(1100); //1.1Ⓝ
      const HELLO_CODE: &[u8] = include_bytes!("./hello.wasm");

      #[near]
      impl Contract {
        pub fn create_hello(&self, prefix: String){
          let account_id = prefix + "." + &env::current_account_id().to_string();
          Promise::new(account_id.parse().unwrap())
            .create_account()
            .transfer(MIN_STORAGE)
            .deploy_contract(HELLO_CODE.to_vec());
        }
      }
    ```
  </Tab>

  <Tab title="🐍 Python">
    ```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
    from near_sdk_py import call, Context, Contract
    from near_sdk_py.promises import Promise 
    from near_sdk_py.constants import ONE_NEAR

    class ExampleContract(Contract):
        @call
        def deploy_contract(self, prefix):
            """Create an account and deploy a contract to it"""
            # This would require loading the contract bytes in Python
            # Load contract bytes - for example purposes only
            # In a real implementation, you'd need to read this from storage or include it
            contract_bytes = b'...'  # This should be actual WASM bytes
            
            MIN_STORAGE = 1.1 * ONE_NEAR  # 1.1Ⓝ
            
            # Generate the new account ID
            account_id = f"{prefix}.{self.current_account_id}"
            
            # Create batch of actions
            return Promise.create_batch(account_id)\
                .create_account()\
                .transfer(MIN_STORAGE)\
                .deploy_contract(contract_bytes)
    ```
  </Tab>

  <Tab title="🐹 GO">
    <Github fname="main.go" language="go" url="https://github.com/Emir-Asanov/near-go-examples/blob/example-release-1/actions/main.go" start="119" end="129" />
  </Tab>
</Tabs>

<Tip>
  If an account with a contract deployed does **not** have any access keys, this is known as a locked contract. When the account is locked, it cannot sign transactions therefore, actions can **only** be performed from **within** the contract code.
</Tip>

***

## Add Keys

When you use actions to create a new account, the created account does not have any [access keys](../../protocol/accounts-contracts/access-keys), meaning that it **cannot sign transactions** (e.g. to update its contract, delete itself, transfer money).

There are two options for adding keys to the account:

1. `add_access_key`: adds a key that can only call specific methods on a specified contract.
2. `add_full_access_key`: adds a key that has full access to the account.

<br />

<Tabs>
  <Tab title="🦀 Rust">
    ```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
      use near_sdk::{near, env, Promise, NearToken, PublicKey};

      #[near(serializers = [json, borsh])]
      #[derive(Default)]
      pub struct Contract { }

      const MIN_STORAGE: NearToken = NearToken::from_millinear(1100); //1.1Ⓝ
      const HELLO_CODE: &[u8] = include_bytes!("./hello.wasm");

      #[near]
      impl Contract {
        pub fn create_hello(&self, prefix: String, public_key: PublicKey){
          let account_id = prefix + "." + &env::current_account_id().to_string();
          Promise::new(account_id.parse().unwrap())
            .create_account()
            .transfer(MIN_STORAGE)
            .deploy_contract(HELLO_CODE.to_vec())
            .add_full_access_key(public_key);
        }
      }
    ```
  </Tab>

  <Tab title="🌐 JavaScript">
    ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
      import { NearBindgen, near, call, NearPromise } from 'near-sdk-js'
      import { PublicKey } from 'near-sdk-js/lib/types'

      const MIN_STORAGE: bigint = BigInt("1000000000000000000000") // 0.001Ⓝ

      @NearBindgen({})
      class Contract {
        @call({})
        create_hello({prefix, public_key}:{prefix: String, public_key: PublicKey}) {
          const account_id = `${prefix}.${near.currentAccountId()}`

          NearPromise.new(account_id)
          .createAccount()
          .transfer(MIN_STORAGE)
          .addFullAccessKey(public_key)
        }
      }
    ```
  </Tab>

  <Tab title="🐍 Python">
    ```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
    from near_sdk_py import call, Contract
    from near_sdk_py.promises import Promise
    from near_sdk_py.constants import ONE_NEAR

    # Minimum amount needed for storage
    MIN_STORAGE = ONE_NEAR // 1000  # 0.001Ⓝ

    class ExampleContract(Contract):
        @call
        def create_with_key(self, prefix, public_key):
            """Create a subaccount with a full access key"""
            # Generate the new account ID
            account_id = f"{prefix}.{self.current_account_id}"
            
            # Create the new account, transfer some NEAR, and add a key
            return Promise.create_batch(account_id)\
                .create_account()\
                .transfer(MIN_STORAGE)\
                .add_full_access_key(public_key)
    ```
  </Tab>

  <Tab title="🐹 GO">
    <Github fname="main.go" language="go" url="https://github.com/Emir-Asanov/near-go-examples/blob/example-release-1/actions/main.go" start="133" end="148" />
  </Tab>
</Tabs>

Notice that what you actually add is a "public key". Whoever holds its private counterpart, i.e. the private-key, will be able to use the newly access key.

<Tip>
  If an account with a contract deployed does **not** have any access keys, this is known as a locked contract. When the account is locked, it cannot sign transactions therefore, actions can **only** be performed from **within** the contract code.
</Tip>

***

## Delete Account

There are two scenarios in which you can use the `delete_account` action:

1. As the **last** action in a chain of batched actions.
2. To make your smart contract delete its own account.

<Tabs>
  <Tab title="🦀 Rust">
    ```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
      use near_sdk::{near, env, Promise, NearToken, AccountId};

      #[near(contract_state)]
      #[derive(Default)]
      pub struct Contract { }

      const MIN_STORAGE: NearToken = NearToken::from_millinear(1); //0.001Ⓝ

      #[near]
      impl Contract {
        pub fn create_delete(&self, prefix: String, beneficiary: AccountId){
          let account_id = prefix + "." + &env::current_account_id().to_string();
          Promise::new(account_id.parse().unwrap())
            .create_account()
            .transfer(MIN_STORAGE)
            .delete_account(beneficiary);
        }

        pub fn self_delete(beneficiary: AccountId){
          Promise::new(env::current_account_id())
            .delete_account(beneficiary);
        }
      }
    ```
  </Tab>

  <Tab title="🌐 JavaScript">
    ```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
      import { NearBindgen, near, call, NearPromise } from 'near-sdk-js'
      import { AccountId } from 'near-sdk-js/lib/types'

      const MIN_STORAGE: bigint = BigInt("1000000000000000000000") // 0.001Ⓝ

      @NearBindgen({})
      class Contract {
        @call({})
        create_delete({prefix, beneficiary}:{prefix: String, beneficiary: AccountId}) {
          const account_id = `${prefix}.${near.currentAccountId()}`

          NearPromise.new(account_id)
          .createAccount()
          .transfer(MIN_STORAGE)
          .deleteAccount(beneficiary)
        }

        @call({})
        self_delete({beneficiary}:{beneficiary: AccountId}) {
          NearPromise.new(near.currentAccountId())
          .deleteAccount(beneficiary)
        }
      }
    ```
  </Tab>

  <Tab title="🐍 Python">
    ```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
    from near_sdk_py import call, Contract
    from near_sdk_py.promises import Promise
    from near_sdk_py.constants import ONE_NEAR

    # Minimum amount needed for storage
    MIN_STORAGE = ONE_NEAR // 1000  # 0.001Ⓝ

    class ExampleContract(Contract):
        @call
        def create_delete(self, prefix, beneficiary):
            """Create an account and immediately delete it, sending funds to a beneficiary"""
            # Generate the new account ID
            account_id = f"{prefix}.{self.current_account_id}"
            
            # Create the account, transfer funds, then delete it
            return Promise.create_batch(account_id)\
                .create_account()\
                .transfer(MIN_STORAGE)\
                .delete_account(beneficiary)
        
        @call
        def self_delete(self, beneficiary):
            """Delete this contract's account"""
            # Delete the account and send remaining funds to beneficiary
            return Promise.create_batch(self.current_account_id)\
                .delete_account(beneficiary)
    ```
  </Tab>

  <Tab title="🐹 GO">
    <Github fname="main.go" language="go" url="https://github.com/Emir-Asanov/near-go-examples/blob/example-release-1/actions/main.go" start="162" end="179" />
  </Tab>
</Tabs>

<Warning>
  **Token Loss**
  If the beneficiary account does not exist the funds will be [**dispersed among validators**](../../protocol/network/token-loss).
</Warning>

<Warning>
  **Token Loss**
  Do **not** use `delete` to try fund a new account. Since the account doesn't exist the tokens will be lost.
</Warning>
