Let's say we initialize near like so and that the user is already logged in:
const near = await window.nearlib.connect(Object.assign({ deps: { keyStore: new window.nearlib.keyStores.BrowserLocalStorageKeyStore() } }, window.nearConfig));
const walletAccount = new window.nearlib.WalletAccount(near);
I want to be able to get an account's NEAR balance using something like:
near.getBalanceOf(walletAccount.getAccountId()).then(...)
or maybe
walletAccount.getBalance().then(...)
WalletAccount is just used to login with the wallet. All the relevant API is located in Account class. Here is a way to query your own account info:
let account = await near.account(walletAccount.getAccountId());
console.log(await account.state());
The result will be something like this:
{
"amount":"20999000097842111450",
"code_hash":"11111111111111111111111111111111",
"staked":"2000000000",
"storage_paid_at":324708,
"storage_usage":551
}
Related
I have created a bot that allows, among other things, to send a message to those who belong to a certain role.
The bot is hosted on Heroku (free version, with a mandatory restart every day)
When I try to retrieve the members of the role in question I have the impression to retrieve only the members who are connected since the bot restart (or who have been online).
I have 27 members of a role but the bot retrieves only 3
screenshot members discord
data in debug
Here is my code :
client.on("messageCreate", message =>{
message.guild.roles.fetch(roleMembersId).then(role => {
role.members.forEach(member => {
console.log("user "+ member.user.username)
})
})
})
I have the same behavior if I use interactions or directly the client
Is there a solution to this problem? I did not find anything like this when I searched
Perhaps you're missing the GUILD_PRESENCES intent.
For discord.js v14:
const { Client, GatewayIntentBits, Partials } = require('discord.js');
const client = new Client({
intents: [
GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.GuildPresences
]
})
For lower versions you can try and use:
const Discord = require("discord.js");
const client = new Discord.Client({
intents: [
'GUILDS','GUILD_MESSAGES','GUILD_PRESENCES'
]
});
Role#members only returns cached members, as you can see in the description, and source. You can fetch all members (and cache them) first, before using it
await message.guild.members.fetch()
const members = message.guild.roles.cache.get(roleId).members
members.forEach(m => console.log(`user ${m.user.username}`))
I have set up node:
nearup run localnet --binary-path ~/code/nearcore/target/release
I am trying to run a jest test case:
beforeAll(async function () {
// NOTE: nearlib and nearConfig are made available by near-cli/test_environment
const near = await nearlib.connect(nearConfig)
})
However there is obvious step missing how to create test accounts on your local node. This is the error:
● Test suite failed to run
Can not sign transactions for account test.near, no matching key pair found in Signer.
at node_modules/near-api-js/lib/account.js:83:23
at Object.exponentialBackoff [as default] (node_modules/near-api-js/lib/utils/exponential-backoff.js:7:24)
at Account.signAndSendTransaction (node_modules/near-api-js/lib/account.js:80:24)
at Account.createAndDeployContract (node_modules/near-api-js/lib/account.js:176:9)
at LocalTestEnvironment.setup (node_modules/near-cli/test_environment.js:39:9)
Also looks like near-js-api is hardcoded to deploy only one contract. I need to test multiple contracts. How can I deploy multiple contracts? From near-js-api test_environment.js
class LocalTestEnvironment extends NodeEnvironment {
constructor(config) {
super(config);
}
async setup() {
this.global.nearlib = require('near-api-js');
this.global.nearAPI = require('near-api-js');
this.global.window = {};
let config = require('./get-config')();
this.global.testSettings = this.global.nearConfig = config;
const now = Date.now();
// create random number with at least 7 digits
const randomNumber = Math.floor(Math.random() * (9999999 - 1000000) + 1000000);
config = Object.assign(config, {
contractName: 'test-account-' + now + '-' + randomNumber,
accountId: 'test-account-' + now + '-' + randomNumber
});
const keyStore = new nearAPI.keyStores.UnencryptedFileSystemKeyStore(PROJECT_KEY_DIR);
config.deps = Object.assign(config.deps || {}, {
storage: this.createFakeStorage(),
keyStore,
});
const near = await nearAPI.connect(config);
const masterAccount = await near.account(testAccountName);
const randomKey = await nearAPI.KeyPair.fromRandom('ed25519');
const data = [...fs.readFileSync('./out/main.wasm')];
await config.deps.keyStore.setKey(config.networkId, config.contractName, randomKey);
await masterAccount.createAndDeployContract(config.contractName, randomKey.getPublicKey(), data, INITIAL_BALANCE);
await super.setup();
}
near-js-sdk itself is deploying against mysterious shared-test
case 'ci':
return {
networkId: 'shared-test',
nodeUrl: 'https://rpc.ci-testnet.near.org',
masterAccount: 'test.near',
};
How can I deploy multiple contracts?
You can use masterAccount.createAndDeployContract same as test_environment.js. There is nothing special there except some common init - you can instead create whatever accounts / contracts are needed for your tests directly.
near-js-sdk itself is deploying against mysterious shared-test
This is shared network which can be used to run integration tests. Unless you want to keep your dev work private – it is recommended way to run tests (as hits most realistic environment currently available for testing).
However there is obvious step missing how to create test accounts on your local node.
If you created project using create-near-app you likely have corresponding test.near keys in neardev/ project folder already. That's why above mysterious environment generally works out of box.
For your local environment you need to create test.near yourself:
NODE_ENV=local near create-account test.near --masterAccount some-existing-account
After that you can copy keys to local format (or just reconfigure UnencryptedFileSystemKeyStore to use ~/.near-credentials path):
cp ~/.near-credentials/local/test.near.json project/dir/neardev/local/test.near.json
I'm trying to use Google Classroom API, I've read through their documentation, and the course ID is used for basically everything, but they never explained where to find the course ID for a course.
It also seems like when you create a course, the function would return the course ID, but I'm wondering if it's possible to get the course ID for courses that already exist.
As shown in the quickstart page for the documentation (https://developers.google.com/classroom/quickstart/python), you can run a piece of code to list the first 10 courses the user has access to with their credentials. You can then add a print(course['id']) statement whilst iterating through the courses to print the id of the courses you have retrieved. The python example is shown below
from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/classroom.courses.readonly']
def main():
"""Shows basic usage of the Classroom API.
Prints the names of the first 10 courses the user has access to.
"""
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('classroom', 'v1', credentials=creds)
# Call the Classroom API
results = service.courses().list(pageSize=10).execute()
courses = results.get('courses', [])
if not courses:
print('No courses found.')
else:
print('Courses:')
for course in courses:
print(course['name'])
print(course['id'])
if __name__ == '__main__':
main()
I use this in nodejs/javascript to retrieve all classroom
const { google } = require("googleapis");
const classroom = google.classroom('v1');
const SCOPES = [
"https://www.googleapis.com/auth/classroom.rosters",
"https://www.googleapis.com/auth/classroom.profile.emails",
"https://www.googleapis.com/auth/classroom.profile.photos",
"https://www.googleapis.com/auth/classroom.courses"
];
google.options({
auth: client,
});
//retrieve all classroom
async function getClassroom() {
try {
const res = await classroom.courses.list(
// {
// pageSize: 10,
// pageToken: "",
// }
);
console.log(res.data, "res");
} catch (error) {
console.error("Error:", error.message,);
}
}
Note: The client is my preferred authorization method
I am in the process of writing unit/behavioural tests using Mocha for a particular blockchain network use-case. Based on what I can see, these tests are not hitting the actual fabric, in other words, they seem to be running in some kind of a simulated environment. I don't get to see any of the transactions that took place as a part of the test. Can someone please tell me if it is somehow possible to capture the transactions that take place as part of the Mocha tests?
Initial portion of my code below:
describe('A Network', () => {
// In-memory card store for testing so cards are not persisted to the file system
const cardStore = require('composer-common').NetworkCardStoreManager.getCardStore( { type: 'composer-wallet-inmemory' } );
let adminConnection;
let businessNetworkConnection;
let businessNetworkDefinition;
let businessNetworkName;
let factory;
//let clock;
// Embedded connection used for local testing
const connectionProfile = {
name: 'hlfv1',
'x-type': 'hlfv1',
'version': '1.0.0'
};
before(async () => {
// Generate certificates for use with the embedded connection
const credentials = CertificateUtil.generate({ commonName: 'admin' });
// PeerAdmin identity used with the admin connection to deploy business networks
const deployerMetadata = {
version: 1,
userName: 'PeerAdmin',
roles: [ 'PeerAdmin', 'ChannelAdmin' ]
};
const deployerCard = new IdCard(deployerMetadata, connectionProfile);
console.log("line 63")
const deployerCardName = 'PeerAdmin';
deployerCard.setCredentials(credentials);
console.log("line 65")
// setup admin connection
adminConnection = new AdminConnection({ cardStore: cardStore });
console.log("line 69")
await adminConnection.importCard(deployerCardName, deployerCard);
console.log("line 70")
await adminConnection.connect(deployerCardName);
console.log("line 71")
});
Earlier, my connection profile was using the embedded mode, which I changed to hlfv1 after looking at the answer below. Now, I am getting the error: Error: the string "Failed to import identity. Error: Client.createUser parameter 'opts mspid' is required." was thrown, throw an Error :). This is coming from
await adminConnection.importCard(deployerCardName, deployerCard);. Can someone please tell me what needs to be changed. Any documentation/resource will be helpful.
Yes you can use a real Fabric. Which means you could interact with the created transactions using your test framework or indeed other means such as REST or Playground etc.
In Composer's own test setup, the option for testing against an hlfv1 Fabric environment is used in its setup (ie whether you want to use embedded, web or real Fabric) -> see https://github.com/hyperledger/composer/blob/master/packages/composer-tests-functional/systest/historian.js#L120
Setup is captured here
https://github.com/hyperledger/composer/blob/master/packages/composer-tests-functional/systest/testutil.js#L192
Example of setting up artifacts that you would need to setup to use a real Fabric here
https://github.com/hyperledger/composer/blob/master/packages/composer-tests-functional/systest/testutil.js#L247
Also see this blog for more guidelines -> https://medium.com/#mrsimonstone/debug-your-blockchain-business-network-using-hyperledger-composer-9bea20b49a74
There is some way to create domains in google admin console via a rest api (or some python google-sdk). I search in google documentation but i couldn't find anything.
Yes, take a look at their api. You need of course to be a gapps reseller. https://developers.google.com/admin-sdk/reseller/
Yes, an exemple with Node :
https://cloud.google.com/nodejs/docs/reference/domains/latest
import { DomainsClient } from "#google-cloud/domains";
const client = new DomainsClient({
keyFile,
projectId,
});
const [domainRegisterParameters] = await client.retrieveRegisterParameters({
domainName: "example.com",
location,
});
const registerParameters = domainRegisterParameters.registerParameters
await this.client.registerDomain({...}) // it buy the domain name
It seem to be this for python :
https://cloud.google.com/python/docs/reference/domains/latest