Fixing invalid key file path in AnchorUtils.loadEnv()
The problem you are facing is due to a common bug in the AnchorUtils.loadEnv()
function. In your case, the problem lies in the invalid path to the .key
file.
Problem: Invalid key file path
When using sb.AnchorUtils.loadEnv()
, this function loads environment variables and settings from a specified directory. However, you are passing a relative path as the path to the key file:
const { key pair, connection, program } = await sb.AnchorUtils.loadEnv('./target/deploy/');
The environment
object will be searched for in the following directory structure:
./target/deploy/
|- .environment
|- ... (other files)
Note the dot (.
) at the end of .env
, which is invalid. It should be relative to the current working directory or a specified base directory.
Solution: Update the keyfile path
To resolve this issue, update the path to the keyfile to point directly to the key
file:
const { keypair, connection, program } = await sb.AnchorUtils.loadEnv('./target/deploy/.env');
Make sure the .env
file is in a properly specified relative path. In this case, you are already using ./target/deploy/
, so the path should be correct.
Additional tips
- Be careful when using absolute paths in production environments to avoid security issues.
- Consider using environment variables directly instead of loading them from files:
const { keypair, connection } = await sb.AnchorUtils.loadEnv();
This approach eliminates the need for file paths and makes the code more secure.
Example use case
Here is a complete example showing how to solve this problem:
import { AnchorUtils } from 'anchor';
import sb from '@subql/sb';
import { anchorUtil } from './anchor-utils';
const accountAddress = 'your-account-address';
const secret = 'your-secret-word';
const networkName = 'main network';
// Set node URL, cluster name and network type
const nodeUrl = '
const clusterName = 'cluster-name';
const networkType = 'main network';
try {
// Load environment variables
const { keypair, connection } = await anchorUtil.loadEnv();
// Use loaded environment variables
const program = new sb.Program(network_name, node_address, cluster_name);
// Do something with the account and secret...
} catch (error) {
console.error(error);
}
By following these steps and tips, you should be able to resolve the sb.AnchorUtils.loadEnv()
issue and use the keystore path correctly.