Skip to content

Instantly share code, notes, and snippets.

@ilyar
Last active May 28, 2025 08:46
Show Gist options
  • Save ilyar/19bdc04d1aa09ae0fc84eb4297df1a1d to your computer and use it in GitHub Desktop.
Save ilyar/19bdc04d1aa09ae0fc84eb4297df1a1d to your computer and use it in GitHub Desktop.
How do clear the state of a contract on Near protocol?

How do clear the state of a contract on Near protocol?

Prepare

source neardev/dev-account.env
export CONTRACT_NAME=$CONTRACT_NAME

View state

near view-state $CONTRACT_NAME --finality final

Getting only keys:

// file: view_state_keys.js
const nearAPI = require('near-api-js')
const { connect, keyStores } = nearAPI
const keyStore = new keyStores.UnencryptedFileSystemKeyStore(__dirname);
const config = {
  keyStore,
  networkId: 'testnet',
  nodeUrl: 'https://rpc.testnet.near.org',
  walletUrl: 'https://wallet.testnet.near.org',
  helperUrl: 'https://helper.testnet.near.org',
  explorerUrl: 'https://explorer.testnet.near.org',
}

async function main () {
  const near = await connect(config)
  const response = await near.connection.provider.query({
    request_type: 'view_state',
    finality: 'final',
    account_id: process.env.CONTRACT_NAME,
    prefix_base64: '',
  })
  console.log(JSON.stringify({
    // TODO add calc size of data for limit burning 200TGas for one call on contract
    keys: response.values.map(it => it.key)
  }))
}

main().catch(reason => {
  console.error(reason)
})

Add method clean into contract

for more info see near/core-contracts#171

use near_sdk::json_types::Base64VecU8;
#[near_bindgen]
impl Contract {
    #[private]
    #[init(ignore_state)]
    pub fn clean(keys: Vec<Base64VecU8>) {
        for key in keys.iter() {
            env::storage_remove(&key.0);
        }
    }
}

Build and deploy contract:

near deploy ${CONTRACT_NAME} out/main.wasm

Clean state

near --accountId $CONTRACT_NAME call $CONTRACT_NAME clean --base64 "$(node view_state_keys.js | base64 -w0)" --gas 300000000000000
@Bonifface
Copy link

If you need to clear contract state on a Mainnet account, you can use Lantstool — just select the account and key, and the tool will handle it for you automatically.
👉 See how it works: https://www.youtube.com/watch?v=84OlJric7lk&t=9s

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment