Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save dlpigpen/94c5f19d524cc38217789d2781a8f94b to your computer and use it in GitHub Desktop.
Save dlpigpen/94c5f19d524cc38217789d2781a8f94b 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment