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

Open
wants to merge 13 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
28 changes: 12 additions & 16 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 { Account } from "@near-js/accounts";
import { JsonRpcProvider } from "@near-js/providers";

const connection = await connect({
networkId: "testnet",
nodeUrl: "https://test.rpc.fastnear.com",
// Gather details through the RPC Provider
const provider = new JsonRpcProvider({
url: "https://test.rpc.fastnear.com",
});

// Create an account object
const account = await connection.account("example-account.testnet");
const rpcState = await provider.viewAccount("example-account.testnet");
console.log({ rpcState });

// Gets the total, staked and available balance in yoctoNEAR
const accountBalance = await account.getAccountBalance();
console.log(accountBalance);
// Option 2: Use an Account object
const account = new Account("example-account.testnet", provider);
const accountBalance = await account.getBalance();
const accountState = await account.getState();

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

// Gets a list of authorized apps for an account
const accountDetails = await account.getAccountDetails();
console.log(accountDetails);
console.log({ accountState, accountBalance });
44 changes: 20 additions & 24 deletions javascript/examples/batch-actions.js
Original file line number Diff line number Diff line change
@@ -1,36 +1,32 @@
import { connect, keyStores, KeyPair, transactions, utils } from "near-api-js";
import { Account } from "@near-js/accounts";
import { JsonRpcProvider } from "@near-js/providers";
import { KeyPairSigner } from "@near-js/signers";
import { actionCreators } from "@near-js/transactions";
import { NEAR } from "@near-js/tokens";
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);

const connectionConfig = {
networkId: "testnet",
keyStore: myKeyStore,
nodeUrl: "https://test.rpc.fastnear.com",
};
const nearConnection = await connect(connectionConfig);
// Create a signer from a private key string
const privateKey = process.env.PRIVATE_KEY;
const signer = KeyPairSigner.fromSecretKey(privateKey); // ed25519:5Fg2...

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

// Send a batch of actions to a single receiver
// Prepare the actions
const callAction = transactions.functionCall(
"increment", // Method name
[], // Arguments
"30000000000000", // Gas
0, // Deposit
);
const transferAction = transactions.transfer(utils.format.parseNearAmount("1"));
// Create an account object
const accountId = process.env.ACCOUNT_ID;
const account = new Account(accountId, provider, signer); // example-account.testnet

// Send the batch of actions
const batchActionsResult = await account.signAndSendTransaction({
receiverId: "counter.near-examples.testnet",
actions: [callAction, transferAction],
actions: [
actionCreators.functionCall("increment", {}, "30000000000000", 0),
actionCreators.transfer(NEAR.toUnits("0.1"))
],
});

console.log(batchActionsResult);
94 changes: 27 additions & 67 deletions javascript/examples/contract-interaction.js
Original file line number Diff line number Diff line change
@@ -1,80 +1,40 @@
import { connect, keyStores, KeyPair, providers } from "near-api-js";
import { Account } from "@near-js/accounts";
import { JsonRpcProvider } from "@near-js/providers";
import { KeyPairSigner } from "@near-js/signers";

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);
// Create a connection to testnet RPC
const provider = new JsonRpcProvider({
url: "https://test.rpc.fastnear.com",
});

const account = await nearConnection.account(accountId);
const contractId = "guestbook.near-examples.testnet";

// Make a view call to a contract
async function viewContract({
// Make a read-only function call
const totalMessages = await provider.callFunction(
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,
});
"total_messages",
{}
);

// Parse the result
return JSON.parse(Buffer.from(viewCallResult.result).toString());
}
console.log({ totalMessages });

// Use the view call function
const viewCallData = await viewContract({
contractId: "guestbook.near-examples.testnet",
methodName: "total_messages",
});
console.log(viewCallData);
// Create a signer from a private key string
const privateKey = process.env.PRIVATE_KEY;
const signer = KeyPairSigner.fromSecretKey(privateKey); // ed25519:5Fg2...

// If args are required, they can be passed in like this:
// args: {
// from_index: "0",
// limit: "10"
// }
// Create an account object
const accountId = process.env.ACCOUNT_ID;
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: {
text: "Hello, world!",
}, // Arguments for the method
gas: 100000000000000, // Optional: gas limit
attachedDeposit: 0, // Optional: deposit in yoctoNEAR
// Make a function call that modifies state
const result = await account.callFunction({
contractId: contractId,
methodName: "add_message",
args: { text: "Hello, world!" },
});
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
);
console.log(deployResult);
console.log({ result });
49 changes: 18 additions & 31 deletions javascript/examples/create-account-from-seed.js
Original file line number Diff line number Diff line change
@@ -1,40 +1,27 @@
import { connect, keyStores, KeyPair, utils } from "near-api-js";
import { Account } from "@near-js/accounts";
import { JsonRpcProvider } from "@near-js/providers";
import { KeyPairSigner } from "@near-js/signers";
import { NEAR } from "@near-js/tokens";
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);

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 JsonRpcProvider({
url: "https://test.rpc.fastnear.com",
});

const account = await nearConnection.account(accountId);
// Instantiate the account that will create the new account
const signer = KeyPairSigner.fromSecretKey(process.env.PRIVATE_KEY);
const account = new Account(process.env.ACCOUNT_ID, provider, signer);

// Create a .testnet account
// Generate a new account ID based on the current timestamp
const newAccountId = Date.now() + ".testnet";
// Generate a new seed phrase
// Generate a new key
const { seedPhrase, publicKey, secretKey } = generateSeedPhrase();
console.log("Seed phrase", seedPhrase);
console.log("Private key", secretKey);
console.log("Public key", publicKey);
console.log(`Created key ${secretKey} with seed phrase ${seedPhrase}`);

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
});
console.log(createAccountResult);
await account.createTopLevelAccount(
`acc-${Date.now()}.testnet`,
publicKey,
NEAR.toUnits("0.1")
);
57 changes: 0 additions & 57 deletions javascript/examples/create-account.js

This file was deleted.

36 changes: 36 additions & 0 deletions javascript/examples/create-subaccount.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { Account } from "@near-js/accounts";
import { JsonRpcProvider } from "@near-js/providers";
import { KeyPairSigner } from "@near-js/signers";
import { KeyPair } from "@near-js/crypto";
import { NEAR } from "@near-js/tokens";

import dotenv from "dotenv";

dotenv.config({ path: "../.env" });

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

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

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

// Generate a new key pair
const keyPair = KeyPair.fromRandom("ed25519");
const publicKey = keyPair.getPublicKey().toString();

const prefix = Date.now().toString();

await account.createSubAccount(
prefix, // prefix for the sub account (e.g. sub.near.testnet)
publicKey, // ed25519:2ASWc...
NEAR.toUnits("0.1") // Initial balance for new account in yoctoNEAR
);

console.log(`Created ${prefix}.${accountId} with private key ${keyPair.toString()}`)
Loading