# How to use encryption

Methods such as eth\_estimateGas, eth\_call, eth\_sendTransaction should have encrypted `data` field. To do it, you can use <https://www.npmjs.com/package/@swisstronik/utils>

### Example #1. Send encrypted transaction

Let's take a look on sample function that accepts ethers signer, destination address (address of contract or EOA), raw data field and value to be sent within transaction. This function will request node public key to perform ECDH and derive shared encryption key and then will encrypt provided `data` using DEOXYS-II algorithm

```javascript
const { encryptDataField } = require('@swisstronik/utils')

// Encrypts data field and sends encrypted transaction
// * signer – ethers signer with connected provider
// * destination - destination address
// * data – raw (unencrypted) transaction `data` field
// * value – amount of aswtr to be sent within transaction
const sendShieldedTransaction = async (signer, destination, data, value) => {
    // Encrypt transaction data. `encryptDataField` function also returns 
    // used encryption key to be able decrypt node response. It will be useful 
    // in case if you're sending some query (for example, request PERC20 balance)
    const [encryptedData] = await encryptDataField(
        signer.provider.connection.url,
        data,
        // encryptionKey – also you can provide encryption key by yourself
        // if you want to be able to decrypt transaction payload in the future.
        // Otherwise, it will generate random encryption key using `tweetnacl`
        // library
    )

    // Construct and sign transaction with encrypted data. This transaction will
    // be sent as a regular Ethereum transaction
    return await signer.sendTransaction({
        from: signer.address,
        to: destination,
        data: encryptedData,
        value,
    })
}
```

### Example #2. Send encrypted balanceOf request

Let's take a look on two functions which are used to obtain PERC20 token balance

```javascript
const { encryptDataField, decryptNodeResponse } = require('@swisstronik/utils')

// Obtains PERC20 token balance using ethers wallet and contract instance
const getTokenBalance = async (wallet, contract) => {
    const req = await sendSignedShieldedQuery(
      wallet,
      contract.address,
      contract.interface.encodeFunctionData("balanceOf", [wallet.address]),
    );
  
    const balance = contract.interface.decodeFunctionResult("balanceOf", req)[0]
    return balance
}

// Sends signed encrypted query to the node
const sendSignedShieldedQuery = async (wallet, destination, data) => {
    if (!wallet.provider) {
        throw new Error("wallet doesn't contain connected provider")
    }

    // Encrypt call data
    const [encryptedData, usedEncryptedKey] = await encryptDataField(
        wallet.provider.connection.url,
        data
    )

    // Get chain id for signature
    const networkInfo = await wallet.provider.getNetwork()
    const nonce = await wallet.getTransactionCount()

    // We treat signed call as a transaction, but it will be sent using eth_call
    const callData = {
        nonce: ethers.utils.hexValue(nonce), // We use nonce to create some kind of reuse-protection
        to: destination,
        data: encryptedData,
        chainId: networkInfo.chainId,
    }

    // Extract signature values
    const signedRawCallData = await wallet.signTransaction(callData)
    const decoded = ethers.utils.parseTransaction(signedRawCallData)

    // Construct call with signature values
    const signedCallData = {
        nonce: ethers.utils.hexValue(nonce), // We use nonce to create some kind of reuse-protection
        to: decoded.to,
        data: decoded.data,
        v: ethers.utils.hexValue(decoded.v),
        r: ethers.utils.hexValue(decoded.r),
        s: ethers.utils.hexValue(decoded.s),
        chainId: ethers.utils.hexValue(networkInfo.chainId)
    }

    // Do call
    const response = await wallet.provider.send('eth_call', [signedCallData, "latest"])

    // Decrypt call result
    return await decryptNodeResponse(wallet.provider.connection.url, response, usedEncryptedKey)
}
```

Function `getTokenBalance` creates a signature from owner and calls `sendSignedShieldedQuery` to encrypt function data, sign the query, send the call and decrypt the response


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.swisstronik.com/swisstronik-docs/development/guides/deployment-and-interaction-perc-20/how-to-use-encryption.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
