Skip to content

Update examples to the most recent, yet unreleased near-api-js version #6

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 17 commits into from
May 21, 2025
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 7 additions & 11 deletions javascript/examples/account-details.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,17 @@
import { connect } from "near-api-js";
import { PublicAccount, providers } from "near-api-js";

const connection = await connect({
networkId: "testnet",
nodeUrl: "https://test.rpc.fastnear.com",
// Create a connection to testnet RPC
const provider = new providers.JsonRpcProvider({
url: "https://test.rpc.fastnear.com",
});

// Create an account object
const account = await connection.account("example-account.testnet");
const account = new PublicAccount("example-account.testnet", provider);

// Gets the total, staked and available balance in yoctoNEAR
const accountBalance = await account.getAccountBalance();
const accountBalance = await account.getBalance();
console.log(accountBalance);

// Account's state, including its code hash and storage usage
const accountState = await account.state();
const accountState = await account.getInformation();
console.log(accountState);

// Gets a list of authorized apps for an account
const accountDetails = await account.getAccountDetails();
console.log(accountDetails);
30 changes: 17 additions & 13 deletions javascript/examples/batch-actions.js
Original file line number Diff line number Diff line change
@@ -1,30 +1,34 @@
import { connect, keyStores, KeyPair, transactions, utils } from "near-api-js";
import {
Account,
providers,
KeyPairSigner,
transactions,
utils,
} from "near-api-js";
import dotenv from "dotenv";

dotenv.config({ path: "../.env" });
const privateKey = process.env.PRIVATE_KEY;
const accountId = process.env.ACCOUNT_ID;

const myKeyStore = new keyStores.InMemoryKeyStore();
const keyPair = KeyPair.fromString(privateKey);
await myKeyStore.setKey("testnet", accountId, keyPair);
// Create a signer from a private key string
const signer = KeyPairSigner.fromSecretKey(privateKey); // ed25519:5Fg2...

const connectionConfig = {
networkId: "testnet",
keyStore: myKeyStore,
nodeUrl: "https://test.rpc.fastnear.com",
};
const nearConnection = await connect(connectionConfig);
// Create a connection to testnet RPC
const provider = new providers.JsonRpcProvider({
url: "https://test.rpc.fastnear.com",
});

const account = await nearConnection.account(accountId);
// Create an account object
const account = new Account(accountId, provider, signer); // example-account.testnet

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Might be an unpopular opinion, but if signer and provider are always created from just one arg why not just pass those directly into the Account constructor?

const privateKey = process.env.PRIVATE_KEY;
const accountId = process.env.ACCOUNT_ID;
const rpcUrl = process.env.RPC_URL

const account = new Account(accountId, rpcUrl, privateKey);

Might not work for other provider and signer types

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I always end up recreating this util in every single project I work on

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the privateKey makes sense to be honest, the rpcUrl not so much, as a provider might need authentication

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wouldn't change that as I hope in the future the KeyPairSigner won't be the only implementation of Signer
but I like the idea of having a function to create an account in one line, so I suggest we add a static function to an Account

const account = Account.fromPrivateKey(accountId, rpcUrl, privateKey);


// Send a batch of actions to a single receiver
// Prepare the actions
const callAction = transactions.functionCall(
"increment", // Method name
[], // Arguments
{}, // Arguments
"30000000000000", // Gas
0, // Deposit
0 // Deposit
);
const transferAction = transactions.transfer(utils.format.parseNearAmount("1"));

Expand Down
80 changes: 25 additions & 55 deletions javascript/examples/contract-interaction.js
Original file line number Diff line number Diff line change
@@ -1,58 +1,22 @@
import { connect, keyStores, KeyPair, providers } from "near-api-js";
import { Account, providers, KeyPairSigner } from "near-api-js";
import dotenv from "dotenv";
import fs from "fs";

dotenv.config({ path: "../.env" });
const privateKey = process.env.PRIVATE_KEY;
const accountId = process.env.ACCOUNT_ID;

const myKeyStore = new keyStores.InMemoryKeyStore();
const keyPair = KeyPair.fromString(privateKey);
await myKeyStore.setKey("testnet", accountId, keyPair);

const connectionConfig = {
networkId: "testnet",
keyStore: myKeyStore,
nodeUrl: "https://test.rpc.fastnear.com",
};
const nearConnection = await connect(connectionConfig);

const account = await nearConnection.account(accountId);

// Make a view call to a contract
async function viewContract({
contractId,
methodName,
args = {},
finality = "optimistic",
}) {
// Set up a new provider
const url = `https://test.rpc.fastnear.com`;
const provider = new providers.JsonRpcProvider({ url });

// Convert the arguments to base64
const argsBase64 = args
? Buffer.from(JSON.stringify(args)).toString("base64")
: "";

// Make the view call
const viewCallResult = await provider.query({
request_type: "call_function",
account_id: contractId,
method_name: methodName,
args_base64: argsBase64,
finality: finality,
});

// Parse the result
return JSON.parse(Buffer.from(viewCallResult.result).toString());
}
// Create a connection to testnet RPC
const provider = new providers.JsonRpcProvider({
url: "https://test.rpc.fastnear.com",
});

// Use the view call function
const viewCallData = await viewContract({
contractId: "guestbook.near-examples.testnet",
methodName: "total_messages",
});
const viewCallData = await provider.callContractViewFunction(
"guestbook.near-examples.testnet",
"total_messages",
{}
);
console.log(viewCallData);

// If args are required, they can be passed in like this:
Expand All @@ -61,20 +25,26 @@ console.log(viewCallData);
// limit: "10"
// }

// Create a signer from a private key string
const signer = KeyPairSigner.fromSecretKey(privateKey); // ed25519:5Fg2...

// Create an account object
const account = new Account(accountId, provider, signer); // example-account.testnet

// Make a function call to a contract
const contractCallResult = await account.functionCall({
contractId: "guestbook.near-examples.testnet", // Contract account ID
methodName: "add_message", // Method to call
args: {
const contractCallResult = await account.callFunction(
"guestbook.near-examples.testnet",
"add_message",
{
text: "Hello, world!",
}, // Arguments for the method
gas: 100000000000000, // Optional: gas limit
attachedDeposit: 0, // Optional: deposit in yoctoNEAR
});
},
0,
"100000000000000"
);
console.log(contractCallResult);

// Deploy a contract to the account
const deployResult = await account.deployContract(
fs.readFileSync("../contracts/contract.wasm"), // Path of contract WASM relative to the working directory
fs.readFileSync("../contracts/contract.wasm") // Path of contract WASM relative to the working directory
);
console.log(deployResult);
34 changes: 14 additions & 20 deletions javascript/examples/create-account-from-seed.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,21 @@
import { connect, keyStores, KeyPair, utils } from "near-api-js";
import { Account, providers, KeyPairSigner, utils } from "near-api-js";
import { generateSeedPhrase } from "near-seed-phrase";
import dotenv from "dotenv";

dotenv.config({ path: "../.env" });
const privateKey = process.env.PRIVATE_KEY;
const accountId = process.env.ACCOUNT_ID;

const myKeyStore = new keyStores.InMemoryKeyStore();
const keyPair = KeyPair.fromString(privateKey);
await myKeyStore.setKey("testnet", accountId, keyPair);
// Create a signer from a private key string
const signer = KeyPairSigner.fromSecretKey(privateKey); // ed25519:5Fg2...

const connectionConfig = {
networkId: "testnet",
keyStore: myKeyStore,
nodeUrl: "https://test.rpc.fastnear.com",
};
const nearConnection = await connect(connectionConfig);
// Create a connection to testnet RPC
const provider = new providers.JsonRpcProvider({
url: "https://test.rpc.fastnear.com",
});

const account = await nearConnection.account(accountId);
// Create an account object
const account = new Account(accountId, provider, signer); // example-account.testnet

// Create a .testnet account
// Generate a new account ID based on the current timestamp
Expand All @@ -28,13 +26,9 @@ console.log("Seed phrase", seedPhrase);
console.log("Private key", secretKey);
console.log("Public key", publicKey);

const createAccountResult = await account.functionCall({
contractId: "testnet",
methodName: "create_account",
args: {
new_account_id: newAccountId, // example-account.testnet
new_public_key: publicKey, // ed25519:2ASWc...
},
attachedDeposit: utils.format.parseNearAmount("0.1"), // Initial balance for new account in yoctoNEAR
});
const createAccountResult = await account.createTopLevelAccount(
newAccountId,
publicKey,
utils.format.parseNearAmount("0.1")
);
console.log(createAccountResult);
42 changes: 18 additions & 24 deletions javascript/examples/create-account.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,20 @@
import { connect, keyStores, KeyPair, utils } from "near-api-js";
import { Account, providers, KeyPairSigner, KeyPair, utils } from "near-api-js";
import dotenv from "dotenv";

dotenv.config({ path: "../.env" });
const privateKey = process.env.PRIVATE_KEY;
const accountId = process.env.ACCOUNT_ID;

const myKeyStore = new keyStores.InMemoryKeyStore();
const keyPair = KeyPair.fromString(privateKey);
await myKeyStore.setKey("testnet", accountId, keyPair);
// Create a signer from a private key string
const signer = KeyPairSigner.fromSecretKey(privateKey); // ed25519:5Fg2...

const connectionConfig = {
networkId: "testnet",
keyStore: myKeyStore,
nodeUrl: "https://test.rpc.fastnear.com",
};
const nearConnection = await connect(connectionConfig);
// Create a connection to testnet RPC
const provider = new providers.JsonRpcProvider({
url: "https://test.rpc.fastnear.com",
});

const account = await nearConnection.account(accountId);
// Create an account object
const account = new Account(accountId, provider, signer); // example-account.testnet

// Create a .testnet account
// Generate a new account ID based on the current timestamp
Expand All @@ -28,30 +26,26 @@ const newPrivateKey = newKeyPair.toString();
console.log("Private key", newPrivateKey);
console.log("Public key", newPublicKey);

const createAccountResult = await account.functionCall({
contractId: "testnet",
methodName: "create_account",
args: {
new_account_id: newAccountId, // example-account.testnet
new_public_key: newPublicKey, // ed25519:2ASWc...
},
attachedDeposit: utils.format.parseNearAmount("0.1"), // Initial balance for new account in yoctoNEAR
});
const createAccountResult = await account.createTopLevelAccount(
newAccountId,
newPublicKey, // ed25519:2ASWc...
utils.format.parseNearAmount("0.1") // Initial balance for new account in yoctoNEAR
);
console.log(createAccountResult);

// Create a sub account
// Generate a new sub account ID based on the current timestamp
const newSubAccountId = Date.now() + "." + accountId;
const newSubAccountIdPrefix = Date.now().toString();
// Generate a new key pair
const newSubKeyPair = KeyPair.fromRandom("ed25519");
const newSubPublicKey = newSubKeyPair.getPublicKey().toString();
const newSubPrivateKey = newSubKeyPair.toString();
console.log("Private key", newSubPrivateKey);
console.log("Public key", newSubPublicKey);

const createSubAccountResult = await account.createAccount(
newSubAccountId, // sub.example-account.testnet
const createSubAccountResult = await account.createSubAccount(
newSubAccountIdPrefix,
newSubPublicKey, // ed25519:2ASWc...
utils.format.parseNearAmount("0.1"), // Initial balance for new account in yoctoNEAR
utils.format.parseNearAmount("0.1") // Initial balance for new account in yoctoNEAR
);
console.log(createSubAccountResult);
53 changes: 26 additions & 27 deletions javascript/examples/delete-account.js
Original file line number Diff line number Diff line change
@@ -1,47 +1,46 @@
import { connect, keyStores, KeyPair, utils } from "near-api-js";
import { Account, providers, KeyPairSigner, KeyPair, utils } from "near-api-js";
import dotenv from "dotenv";

dotenv.config({ path: "../.env" });
const privateKey = process.env.PRIVATE_KEY;
const beneficiaryAccountId = process.env.ACCOUNT_ID;

const myKeyStore = new keyStores.InMemoryKeyStore();
const keyPair = KeyPair.fromString(privateKey);
await myKeyStore.setKey("testnet", beneficiaryAccountId, keyPair);
// Create a signer from a private key string
const signer = KeyPairSigner.fromSecretKey(privateKey); // ed25519:5Fg2...

const connectionConfig = {
networkId: "testnet",
keyStore: myKeyStore,
nodeUrl: "https://test.rpc.fastnear.com",
};
const nearConnection = await connect(connectionConfig);
// Create a connection to testnet RPC
const provider = new providers.JsonRpcProvider({
url: "https://test.rpc.fastnear.com",
});

const accountCreator = await nearConnection.account(beneficiaryAccountId);
// Create an account object
const account = new Account(beneficiaryAccountId, provider, signer); // example-account.testnet

// First create a new account to be deleted
// Generate a new account ID based on the current timestamp
const accountToDeleteId = Date.now() + ".testnet";
const newKeyPair = KeyPair.fromRandom("ed25519");
const newPublicKey = newKeyPair.getPublicKey().toString();

await accountCreator.functionCall({
contractId: "testnet",
methodName: "create_account",
args: {
new_account_id: accountToDeleteId,
new_public_key: newPublicKey,
},
gas: "300000000000000",
attachedDeposit: utils.format.parseNearAmount("0.1"),
});
await account.createTopLevelAccount(
accountToDeleteId,
newPublicKey,
utils.format.parseNearAmount("0.1")
);

// Create a signer from a key pair that was added to new account
const signerToDelete = new KeyPairSigner(newKeyPair);

// Create an account object for the new account
// and add the new key pair to the keystore
const accountToDelete = await nearConnection.account(accountToDeleteId);
await myKeyStore.setKey("testnet", accountToDeleteId, newKeyPair);
// Create an account object for the new account with corresponding signer
const accountToDelete = new Account(
accountToDeleteId,
provider,
signerToDelete
);

// Delete the account with account ID of the account object
// specifying the beneficiary account ID
const deleteAccountResult =
await accountToDelete.deleteAccount(beneficiaryAccountId); // example-beneficiary.testnet
const deleteAccountResult = await accountToDelete.deleteAccount(
beneficiaryAccountId
); // example-beneficiary.testnet
console.log(deleteAccountResult);
Loading