I am trying to build a car auction network with composer playground the error occurs when I am at the stage to make an offer to an auction and after that every new registry I try to make gets this error Reference error: require not defined i am familiar with JavaScript but I am not sure what causing this error .
'use strict';
const AdminConnection = require('composer-admin').AdminConnection;
const BusinessNetworkConnection = require('composer-client').BusinessNetworkConnection;
const { BusinessNetworkDefinition, CertificateUtil, IdCard } = require('composer-common');
const path = require('path');
require('chai').should();
const NS = 'org.acme.vehicle.auction';
describe('CarAuction', () => {
// 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;
before(async () => {
// Embedded connection used for local testing
const connectionProfile = {
name: 'embedded',
'x-type': 'embedded'
};
// 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);
deployerCard.setCredentials(credentials);
const deployerCardName = 'PeerAdmin';
adminConnection = new AdminConnection({ cardStore: cardStore });
await adminConnection.importCard(deployerCardName, deployerCard);
await adminConnection.connect(deployerCardName);
});
beforeEach(async () => {
businessNetworkConnection = new BusinessNetworkConnection({ cardStore: cardStore });
const adminUserName = 'admin';
let adminCardName;
let businessNetworkDefinition = await BusinessNetworkDefinition.fromDirectory(path.resolve(__dirname, '..'));
// Install the Composer runtime for the new business network
await adminConnection.install(businessNetworkDefinition);
// Start the business network and configure an network admin identity
const startOptions = {
networkAdmins: [
{
userName: adminUserName,
enrollmentSecret: 'adminpw'
}
]
};
const adminCards = await adminConnection.start(businessNetworkDefinition.getName(), businessNetworkDefinition.getVersion(), startOptions);
// Import the network admin identity for us to use
adminCardName = `${adminUserName}#${businessNetworkDefinition.getName()}`;
await adminConnection.importCard(adminCardName, adminCards.get(adminUserName));
// Connect to the business network using the network admin identity
await businessNetworkConnection.connect(adminCardName);
});
describe('#makeOffer', () => {
it('should add the offer to the offers of a vehicle listing', async () => {
const factory = businessNetworkConnection.getBusinessNetwork().getFactory();
// create the auctioneer
const seller = factory.newResource(NS, 'Member', 'daniel.selman#example.com');
seller.firstName = 'Dan';
seller.lastName = 'Selman';
seller.balance = 0;
// create the vehicle
const vehicle = factory.newResource(NS, 'Vehicle', 'CAR_001');
vehicle.owner = factory.newRelationship(NS, 'Member', seller.$identifier);
// create the vehicle listing
const listing = factory.newResource(NS, 'VehicleListing', 'LISTING_001');
listing.reservePrice = 100;
listing.description = 'My nice car';
listing.state = 'FOR_SALE';
listing.vehicle = factory.newRelationship(NS, 'Vehicle', 'CAR_001');
// create the buyer
const buyer = factory.newResource(NS, 'Member', 'sstone1#example.com');
buyer.firstName = 'Simon';
buyer.lastName = 'Stone';
buyer.balance = 1000;
// create another potential buyer
const buyer2 = factory.newResource(NS, 'Member', 'whitemat#example.com');
buyer2.firstName = 'Matthew';
buyer2.lastName = 'White';
buyer2.balance = 100;
// create the auctioneer
const auctioneer = factory.newResource(NS, 'Auctioneer', 'boss#auction.com');
auctioneer.firstName = 'Mr';
auctioneer.lastName = 'Smith';
const offer = factory.newTransaction(NS, 'Offer');
offer.member = factory.newRelationship(NS, 'Member', buyer.$identifier);
offer.listing = factory.newRelationship(NS, 'VehicleListing', 'LISTING_001');
offer.bidPrice = 200;
// Get the registries.
const vehicleRegistry = await businessNetworkConnection.getAssetRegistry(NS + '.Vehicle');
const vehicleListingRegistry = await businessNetworkConnection.getAssetRegistry(NS + '.VehicleListing');
const userRegistry = await businessNetworkConnection.getParticipantRegistry(NS + '.Member');
const auctioneerRegistry = await businessNetworkConnection.getParticipantRegistry(NS + '.Auctioneer');
// Add the Vehicle to the asset registry.
await vehicleRegistry.add(vehicle);
// Add the VehicleListing to the asset registry
await vehicleListingRegistry.add(listing);
// add the members
await userRegistry.addAll([buyer, buyer2, seller]);
// add the auctioneers
await auctioneerRegistry.addAll([auctioneer]);
// Create the offer transaction and submit
await businessNetworkConnection.submitTransaction(offer);
// Create the offer transaction and submit
const lowOffer = factory.newTransaction(NS, 'Offer');
lowOffer.member = factory.newRelationship(NS, 'Member', buyer2.$identifier);
lowOffer.listing = factory.newRelationship(NS, 'VehicleListing', 'LISTING_001');
lowOffer.bidPrice = 50;
await businessNetworkConnection.submitTransaction(lowOffer);
// get the listing
let newListing = await vehicleListingRegistry.get(listing.$identifier);
// both offers should have been added to the listing
newListing.offers.length.should.equal(2);
// close the bidding
const closeBidding = factory.newTransaction(NS, 'CloseBidding');
closeBidding.listing = factory.newRelationship(NS, 'VehicleListing', 'LISTING_001');
await businessNetworkConnection.submitTransaction(closeBidding);
// get the listing
newListing = await vehicleListingRegistry.get(listing.$identifier);
// the offer should have been added to the listing
newListing.state.should.equal('SOLD');
// get the buyer and seller
const theBuyer = await userRegistry.get(buyer.$identifier);
const theSeller = await userRegistry.get(seller.$identifier);
// check the buyer's balance
theBuyer.balance.should.equal(800);
// check the seller's balance
theSeller.balance.should.equal(200);
// get the vehicle
const theVehicle = await vehicleRegistry.get(vehicle.$identifier);
// check that the buyer now owns the car
theVehicle.owner.getIdentifier().should.equal(buyer.$identifier);
});
describe('#closeBidding', () => {
it('with no bids should result in RESERVE_NOT_MET', async () => {
const factory = businessNetworkConnection.getBusinessNetwork().getFactory();
const seller = factory.newResource(NS, 'Member', 'daniel.selman#example.com');
seller.firstName = 'Dan';
seller.lastName = 'Selman';
seller.balance = 0;
// create the vehicle
const vehicle = factory.newResource(NS, 'Vehicle', 'CAR_001');
vehicle.owner = factory.newRelationship(NS, 'Member', seller.$identifier);
// create the vehicle listing
const listing = factory.newResource(NS, 'VehicleListing', 'LISTING_001');
listing.reservePrice = 100;
listing.description = 'My nice car';
listing.state = 'FOR_SALE';
listing.vehicle = factory.newRelationship(NS, 'Vehicle', vehicle.$identifier);
// Get the registries.
const vehicleRegistry = await businessNetworkConnection.getAssetRegistry(NS + '.Vehicle');
const vehicleListingRegistry = await businessNetworkConnection.getAssetRegistry(NS + '.VehicleListing');
const userRegistry = await businessNetworkConnection.getParticipantRegistry(NS + '.Member');
// Add the Vehicle to the asset registry.
await vehicleRegistry.add(vehicle);
// add the seller to the member registry
await userRegistry.add(seller);
// add the vehicle listing
await vehicleListingRegistry.add(listing);
// close the bidding
const closeBidding = factory.newTransaction(NS, 'CloseBidding');
closeBidding.listing = factory.newRelationship(NS, 'VehicleListing', listing.$identifier);
await businessNetworkConnection.submitTransaction(closeBidding);
// get the listing and check state
const vehicleListing = await vehicleListingRegistry.get(listing.$identifier);
vehicleListing.state.should.equal('RESERVE_NOT_MET');
});
});
});
});
You can't use require in a hyperledger composer business network implementation as you see you get an error because the require keyword is not available.
If you want to learn about blockchain technology then you should not use hyperledger composer because it isn't a blockchain technology. Hyperledger Fabric is a blockchain technology and that would be far more worthwhile investing time to understand.
Hyperledger composer was a framework for business networks that could use hyperledger fabric blockchain technology to provide the persistence, immutability etc of the information that it wanted to store
Related
In Mongoose, we can add methods to documents as follows:
const userSchema = new mongoose.Schema({
balance: Number
})
userSchema.methods.withdrawBalance = function(amount){
const doc = this
doc.balance = doc.balance - amount
}
and we can use it as follows:
const userDoc = UserModel.findById(ID_HERE);
userDoc.deductBalance(100); // -100$ USD
userDoc.save()
I want to be able to do the same on the models the same way I can do it on documents, I want to be able to something like that:
const userDoc = UserModel.findById(ID_HERE).myCustomMethod()
But How?
Hm I am not sure if I get you right but lets try.
const Order = mongoose.model("Order", orderSchema);
Order.test = function(){
console.log("Here I am!");
}
(async () => {
const o = await Order.findOne({}).test();
});
I am trying to swap ETH for DAI tokens using the UniSwap SDK and javascript, but am getting the following error on running the script.
(node:10096) UnhandledPromiseRejectionWarning: Error: resolver or addr is not configured for ENS name (argument="name", value="", code=INVALID_ARGUMENT, version=contracts/5.0.5)
I have narrowed the error down to the uniswap.swapExactETHForTokens function but I still don't know how to fix it.
Full code: (Private keys are hidden from the code for obvious reasons)
const { ChainId, Fetcher, WETH, Route, Trade, TokenAmount, TradeType, Percent } = require('#uniswap/sdk');
const ethers = require('ethers');
const chainId = ChainId.MAINNET;
const tokenAddress = '0x6B175474E89094C44Da98b954EedeAC495271d0F';
const init = async () => {
const dai = await Fetcher.fetchTokenData(chainId, tokenAddress);
const weth = WETH[chainId];
const pair = await Fetcher.fetchPairData(dai, weth);
const route = new Route([pair], weth);
const trade = new Trade(route, new TokenAmount(weth, '1000000000000'), TradeType.EXACT_INPUT);
const slippageTolerance = new Percent('50', '10000');
const amountOutMin = trade.minimumAmountOut(slippageTolerance).raw;
const path = [weth.address, dai.address];
const to = '';
const deadline = Math.floor(Date.now() / 1000) + 60 * 20;
const value = trade.inputAmount.raw;
const provider = ethers.getDefaultProvider('mainnet', {
infura: 'https://mainnet.infura.io/v3/ba14d1b3cfe5405088ee3c65ebd1d4'
});
const signer = new ethers.Wallet(PRIVATE_KEY);
const account = signer.connect(provider);
const uniswap = new ethers.Contract(
'0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D',
['function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts)'],
account
);
const tx = await uniswap.swapExactETHForTokens(
amountOutMin,
path,
to,
deadline,
{ value, gasPrice: 20e9 }
);
console.log(`Transaction hash: ${tx.hash}`);
const receipt = await tx.wait();
console.log(`Transaction was mined in block ${receipt.blockNumber}`);
}
init();
I guess you can replace
const to = ''
by:
const to = process.env.ACCOUNT
providing your account / wallet address to which the targetTokens shall be sent.
In my case, I had directly copy-pasted the router address from the uniswap documentation. So my variable looked something like this:
const routerAddress = "0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ";
Since there was a space at the end of the string, the ethers.js library confused it for ENS name instead of an address. So I corrected it to this:
const routerAddress = "0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D";
Guess it was a silly mistake, but just watch out for it, in case nothing works!
For those who are facing an INVALID ARGUMENT error, here's what worked for my (using React):
Import router02 :
import UniswapV2Router02 from '#uniswap/v2-periphery/build/UniswapV2Router02.json';
hex function:
const toHex = (currencyAmount) => `0x${currencyAmount.raw.toString(16)}`;
const amountOutMin = toHex(trade.minimumAmountOut(slippageTolerance));
const value = toHex(trade.inputAmount);
connect to blockchain
const provider = ethers.getDefaultProvider('mainnet', {
infura: 'JUST_INFURA_NUMBER eg. xxxxxxxxxx'
});
Get contract and methods:
const abi = UniswapV2Router02['abi'];
const uniswapRouter = new ethers.Contract(
'0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D',
abi,
account); //if this doesnt work, try using provider/signer instead of account
console.log("uniswap contract: ", uniswapRouter);
const tx = await uniswapRouter.swapExactETHForTokens(
amountOutMin,
path,
to,
deadline,
{value, gasPrice: 20e9, gasLimit: 250000}
);
Tutorial code: https://www.youtube.com/watch?v=0Im5iaYoz1Y
I connected the typescript function to Azure Blobstorage through Rest-API and this works fine for me. Now I want to get each blob contents and read the contents of each blobs.
I try this with this code here, but it returns an error:
const blobServiceClient = new BlobServiceClient(`https://${accountName}.blob.core.windows.net?${sasToken}`,
pipeline)
const containerClient = blobServiceClient.getContainerClient(containerName)
console.log(containerClient)
if (!containerClient.exists()) {
console.log("the container does not exit")
await containerClient.create()
}
const client = containerClient.getBlockBlobClient(this.currentFile.name)
//name of uploded blob
console.log(this.currentFile.name)
//metaata from the blob
console.log(client)
//List each blobs in the container
for await (const blob of containerClient.listBlobsFlat()) {
console.log('\t', blob.name);
const blockBlobClient = containerClient.getBlockBlobClient(blob.name);
const downloadBlockBlobResponse = await blockBlobClient.download(0);
console.log('\nDownloaded blob content...');
console.log('\t', await streamToString(downloadBlockBlobResponse.readableStreamBody));
//end of loop
}
async function streamToString(readableStream) {
return new Promise((resolve, reject) => {
const chunks = [];
readableStream.on("data", (data) => {
chunks.push(data.toString());
});
readableStream.on("end", () => {
resolve(chunks.join(""));
});
readableStream.on("error", reject);
});
}
The error is :
ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'on' of undefined TypeError: Cannot read property 'on' of undefined
So how to solve the problem?
Thanks
Download the official sample code.
It runs normally on my side. Check if your local lack of dependencies, or the permissions in the storage need to be set.
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
/*
Setup: Enter your storage account name and shared key in main()
*/
import {
BlobServiceClient,
StorageSharedKeyCredential,
BlobDownloadResponseModel
} from "#azure/storage-blob";
// Load the .env file if it exists
import * as dotenv from "dotenv";
dotenv.config();
export async function main() {
// Enter your storage account name and shared key
const account = process.env.ACCOUNT_NAME || "pans*****age";
const accountKey = process.env.ACCOUNT_KEY || "IHa48xxo+0anyKQ2GzQ2K*******ZBxgJ0VotCpGs/PMftkebb9UFqyg==";
// Use StorageSharedKeyCredential with storage account and account key
// StorageSharedKeyCredential is only available in Node.js runtime, not in browsers
const sharedKeyCredential = new StorageSharedKeyCredential(account, accountKey);
// ONLY AVAILABLE IN NODE.JS RUNTIME
// DefaultAzureCredential will first look for Azure Active Directory (AAD)
// client secret credentials in the following environment variables:
//
// - AZURE_TENANT_ID: The ID of your AAD tenant
// - AZURE_CLIENT_ID: The ID of your AAD app registration (client)
// - AZURE_CLIENT_SECRET: The client secret for your AAD app registration
//
// If those environment variables aren't found and your application is deployed
// to an Azure VM or App Service instance, the managed service identity endpoint
// will be used as a fallback authentication source.
// const defaultAzureCredential = new DefaultAzureCredential();
// You can find more TokenCredential implementations in the [#azure/identity](https://www.npmjs.com/package/#azure/identity) library
// to use client secrets, certificates, or managed identities for authentication.
// Use AnonymousCredential when url already includes a SAS signature
// const anonymousCredential = new AnonymousCredential();
// List containers
const blobServiceClient = new BlobServiceClient(
// When using AnonymousCredential, following url should include a valid SAS or support public access
`https://${account}.blob.core.windows.net`,
sharedKeyCredential
);
let i = 1;
for await (const container of blobServiceClient.listContainers()) {
console.log(`Container ${i++}: ${container.name}`);
}
// Create a container
const containerName = `newcontainer${new Date().getTime()}`;
const containerClient = blobServiceClient.getContainerClient(containerName);
const createContainerResponse = await containerClient.create();
console.log(`Create container ${containerName} successfully`, createContainerResponse.requestId);
// Create a blob
const content = "hello, 你好";
const blobName = "newblob" + new Date().getTime();
const blockBlobClient = containerClient.getBlockBlobClient(blobName);
const uploadBlobResponse = await blockBlobClient.upload(content, Buffer.byteLength(content));
console.log(`Upload block blob ${blobName} successfully`, uploadBlobResponse.requestId);
// List blobs
i = 1;
for await (const blob of containerClient.listBlobsFlat()) {
console.log(`Blob ${i++}: ${blob.name}`);
}
// Get blob content from position 0 to the end
// In Node.js, get downloaded data by accessing downloadBlockBlobResponse.readableStreamBody
// In browsers, get downloaded data by accessing downloadBlockBlobResponse.blobBody
const downloadBlockBlobResponse: BlobDownloadResponseModel = await blockBlobClient.download(0);
console.log(
"Downloaded blob content",
await streamToString(downloadBlockBlobResponse.readableStreamBody!)
);
// Delete container
await containerClient.delete();
console.log("deleted container");
}
// A helper method used to read a Node.js readable stream into string
async function streamToString(readableStream: NodeJS.ReadableStream) {
return new Promise((resolve, reject) => {
const chunks: string[] = [];
readableStream.on("data", (data) => {
chunks.push(data.toString());
});
readableStream.on("end", () => {
resolve(chunks.join(""));
});
readableStream.on("error", reject);
});
}
main().catch((err) => {
console.error("Error running sample:", err.message);
});
I am trying to create a raw transaction for sending to the blockchain. In doing so, I want to do this in a browser.
Where can I get nonWitnessUtxo?
All the information that I have outlined here, I found in the tests.
Am I doing the right thing?
const bitcoin = require('bitcoinjs-lib')
const testnet = bitcoin.networks.testnet
const keyPair = bitcoin.ECPair.makeRandom({ network: testnet })
const publicKey = keyPair.publicKey
const { address } = bitcoin.payments.p2pkh({
pubkey: publicKey,
network: testnet
})
const privateKey = keyPair.toWIF()
const psbt = new bitcoin.Psbt({ network: testnet })
const txid = '226a14d30cfd411b14bf20b7ffd211f7f206699690c54d456cc1bef70c2de5a6'
const key = bitcoin.ECPair.fromWIF(privateKey, testnet)
psbt.addInput({
hash: txid,
index: 0,
nonWitnessUtxo: Buffer.from('Where can i get this?', 'hex')
})
psbt.addOutput({
script: Buffer.from('mmpAPZSvhJs1NGw8UaJXEJ9vRByAxProUL', 'hex')
value: 10000
})
psbt.signInput(0, key)
psbt.validateSignaturesOfInput(0)
psbt.finalizeAllInputs()
psbt.extractTransaction().toHex()
I would be grateful for any help!
The nonWitnessUtxo is the full rawtransaction that you are referencing with the input txid.
This answer is for those looking for a way to create a transaction in the browser, but could not deal with the bitcoinjs-lib
I use bitcore-lib - https://www.npmjs.com/package/bitcore-lib
const bitcore = require('bitcore-lib')
const firstPrivateKey = new bitcore.PrivateKey()
const secondPrivateKey = new bitcore.PrivateKey()
const wif = firstPrivateKey.toString()
const toAddress = secondPrivateKey.toAddress().toString()
const satoshiAmount = 10000
const privateKey = bitcore.PrivateKey.fromWIF(wif)
const sourceAddress = privateKey.toAddress(bitcore.Networks.testnet)
const targetAddress = bitcore.Address.fromString(toAddress)
const utxos = [
{
address: 'mywRqUpbENhbu5VsYDwiMTJouVK9g2ZEJQ',
txid: '761693565e82ca176532c52a37fb38cd9f1eb0172a00562b394e60ede0b7df8a',
vout: 1,
scriptPubKey: '76a914ca133ceac705b723b91263aa163ea8a45954e49a88ac',
amount: 0.0001,
satoshis: 10000,
height: 1578273,
confirmations: 338
}
]
const transaction = new bitcore.Transaction()
transaction.from(utxos)
transaction.to(targetAddress, Number(satoshiAmount))
transaction.change(sourceAddress)
transaction.sign(privateKey)
const serializedTX = tx.serialize()
Then you need send this serializedTX as raw transaction to bitcoin network.
P.S. This example does not work because there is an invalid is presented utxos. Get your utxos using API, such as https://bitpay.com/api/addr/${sourceAddress}/utxo and then everything will work.
I am confused about how I should be executing a contract's method using the web3 1.0 library.
This code works (so long as I manually unlock the account first):
var contract = new web3.eth.Contract(contractJson, contractAddress);
contract.methods
.transfer("0x0e0479bC23a96F6d701D003c5F004Bb0f28e773C", 1000)
.send({
from: "0x2EBd0A4729129b45b23aAd4656b98026cf67650A"
})
.on('confirmation', (confirmationNumber, receipt) => {
io.emit('confirmation', confirmationNumber);
});
I get this error (if I don't unlock manually first):
Returned error: authentication needed: password or unlock
The above code is an API endpoint in node.js, so I want it to unlock or authenticate programmatically.
There is no method in web3.js 1.0 to unlock the account.
I also don't think this is necessary (at least that's what I am confused about). Since I am managing accounts, I know what the private key is.
I am thinking the transaction needs to be signed with the private key?? Is this correct? Is this effectively the same thing as "unlocking the account"?
I tried doing this:
var contract = new web3.eth.Contract(contractJson, contractAddress);
var tx = {
from: "...{fromAddress -- address that has the private key below}",
to: "...",
value: ...
};
var signed = web3.eth.accounts.signTransaction(tx,
"...{privateKey}");
console.log(signed);
var promise = web3.eth.sendSignedTransaction(signed);
I get this error:
Returned error: The method net_version does not exist/is not available
What is the easiest way to authenticate and submit a transaction?
Ideally, I want to use the first approach in my code sample, as it is the cleanest.
This code allows me to sign a transaction server-side (node.js) using the privateKey from the account I created (using web3.eth.accounts.create()), and send the signed transaction to the network without having to unlock the account.
I am using Geth 1.7.1
var contract = new web3.eth.Contract(contractJson, contractAddress);
var transfer = contract.methods.transfer("0x...", 490);
var encodedABI = transfer.encodeABI();
var tx = {
from: "0x...",
to: contractAddress,
gas: 2000000,
data: encodedABI
};
web3.eth.accounts.signTransaction(tx, privateKey).then(signed => {
var tran = web3.eth.sendSignedTransaction(signed.rawTransaction);
tran.on('confirmation', (confirmationNumber, receipt) => {
console.log('confirmation: ' + confirmationNumber);
});
tran.on('transactionHash', hash => {
console.log('hash');
console.log(hash);
});
tran.on('receipt', receipt => {
console.log('reciept');
console.log(receipt);
});
tran.on('error', console.error);
});
A way to be able to call your contract methods without having to sign the transaction explicitly is this (web3js 1.0.0):
const privateKey = 'e0f3440344e4814d0dea8a65c1b9c488bab4295571c72fb879f5c29c8c861937';
const account = web3.eth.accounts.privateKeyToAccount('0x' + privateKey);
web3.eth.accounts.wallet.add(account);
web3.eth.defaultAccount = account.address;
// ...
contract = new web3.eth.Contract(JSON_INTERFACE, address);
contract.methods.myMethod(myParam1, myParam2)
.send({
from: this.web3.eth.defaultAccount,
gas: myConfig.gas,
gasPrice: myConfig.gasPrice
})
Here's a complete example of how to sign a transaction without a local wallet account. Especially useful if you are using infura for the transaction. This was written for
'use strict';
const Web3 = require('web3');
const wsAddress = 'wss://rinkeby.infura.io/ws';
const contractJson = '(taken from solc or remix online compiler)';
const privateKey = '0xOOOX';
const contractAddress = '0xOOOX';
const walletAddress = '0xOOOX';
const webSocketProvider = new Web3.providers.WebsocketProvider(wsAddress);
const web3 = new Web3(new Web3.providers.WebsocketProvider(webSocketProvider));
const contract = new web3.eth.Contract(
JSON.parse(contractJson),
contractAddress
);
// change this to whatever contract method you are trying to call, E.G. SimpleStore("Hello World")
const query = contract.methods.SimpleStore('Hello World');
const encodedABI = query.encodeABI();
const tx = {
from: walletAddress,
to: contractAddress,
gas: 2000000,
data: encodedABI,
};
const account = web3.eth.accounts.privateKeyToAccount(privateKey);
console.log(account);
web3.eth.getBalance(walletAddress).then(console.log);
web3.eth.accounts.signTransaction(tx, privateKey).then(signed => {
const tran = web3.eth
.sendSignedTransaction(signed.rawTransaction)
.on('confirmation', (confirmationNumber, receipt) => {
console.log('=> confirmation: ' + confirmationNumber);
})
.on('transactionHash', hash => {
console.log('=> hash');
console.log(hash);
})
.on('receipt', receipt => {
console.log('=> reciept');
console.log(receipt);
})
.on('error', console.error);
});
Using
"web3": "1.0.0-beta.30"
This is my implementation using "#truffle/hdwallet-provider": "^2.0.3", "web3": "^1.6.1",
function getWeb3Provider() {
return new HDWalletProvider({
privateKeys: [NFT_MINTER_ACCOUNT_PRIVATE_KEY],
providerOrUrl: BSC_RPC_ENDPOINT,
});
}
const web3 = new Web3(BSC_RPC_ENDPOINT);
const contract = new web3.eth.Contract(
jsonContractABI as unknown as AbiItem[],
NFT_CONTRACT_ADDRESS
);
contract.setProvider(getWeb3Provider());
then in send methods
contract.methods.safeMint(receiverAddress, itemUri).send({
from: NFT_MINTER_ACCOUNT,
});
in call methods
contract.methods.balanceOf(address).call();