Ethereum use ethereumjs-tx create transaction, and sendRawTransaction, buy no effect - ethereum

I was create a transaction, use the following code:
var Tx = require('ethereumjs-tx')
var rawTx = {
nonce: '0x100004',
gasPrice: '0x4a817c800', //0.00000002
gasLimit: '0x15f90', //90000
from: '0x1911c081b0a2359d77d1f858bf5b5b04a080f2bb',
to: '0x5f56bba9ee673d0c7bccf4be1a78b9db3a51114d',
value: '0x2386f26fc10000', // 0.01
data: '0x'
}
var tx = new Tx(rawTx)
tx.sign(privateKey)
var serializedTx = tx.serialize()
var signData = serializedTx.toString('hex');
console.log(signData)
output tx data
f86f831000048504a817c80083015f90945f56bba9ee673d0c7bccf4be1a78b9db3a51114d872386f26fc10000801ba08aacd5525b240df3149ead81c2fd4bf3d2c01cc81506a5442f727f92850c4935a07807e5a74e1994a4fce6727fa9422e34d5da83411a8065c14249e9b5845cac3e
then Broadcast Raw Transaction on http://testnet.etherscan.io/pushTx
show following message
{ "jsonrpc": "2.0", "id": 1, "result": "0x15b9ff6eca21cfe48e853458908abf53ccae131a9aeb4eb03d553281c77c1f89" }
```
but, I open the http://testnet.etherscan.io/tx/0x15b9ff6eca21cfe48e853458908abf53ccae131a9aeb4eb03d553281c77c1f89 , it can found, why?
In addition, I try call sendRawTransaction in the geth console with --testnet
eth.getTransaction(eth.sendRawTransaction('f86f831000048504a817c80083015f90945f56bba9ee673d0c7bccf4be1a78b9db3a51114d872386f26fc10000801ba08aacd5525b240df3149ead81c2fd4bf3d2c01cc81506a5442f727f92850c4935a07807e5a74e1994a4fce6727fa9422e34d5da83411a8065c14249e9b5845cac3e'))
return the info following
{
blockHash: "0x0000000000000000000000000000000000000000000000000000000000000000
",
blockNumber: null,
from: "0x1911c081b0a2359d77d1f858bf5b5b04a080f2bb",
gas: 90000,
gasPrice: 20000000000,
hash: "0x15b9ff6eca21cfe48e853458908abf53ccae131a9aeb4eb03d553281c77c1f89",
input: "0x",
nonce: 1048580,
to: "0x5f56bba9ee673d0c7bccf4be1a78b9db3a51114d",
transactionIndex: null,
value: 10000000000000000
}
All the operation in the test network, Data seems to be correct, but no effect, What did I missed?

Related

Converting Stripe API syntax to Google Apps Script

This SO answer correctly explains that since the require Node/JS library is not supported by Google Apps Script, the following code changes must be made to get Stripe to work properly in a GAS project:
from
const stripe = require('stripe')('sk_test_4eC39HqLyjWDarjtT1zdp7dc');
(async () => {
const product = await stripe.products.create({
name: 'My SaaS Platform',
type: 'service',
});
})();
to
function myFunction() {
var url = "https://api.stripe.com/v1/products";
var params = {
method: "post",
headers: {Authorization: "Basic " + Utilities.base64Encode("sk_test_4eC39HqLyjWDarjtT1zdp7dc:")},
payload: {name: "My SaaS Platform", type: "service"}
};
var res = UrlFetchApp.fetch(url, params);
Logger.log(res.getContentText())
}
Now, I want to convert the following code into the Google Apps Script friendly version.
from https://stripe.com/docs/payments/checkout/accept-a-payment#create-checkout-session
const stripe = require('stripe')('sk_test_4eC39HqLyjWDarjtT1zdp7dc');
const session = await stripe.checkout.sessions.create({
payment_method_types: ['card', 'ideal'],
line_items: [{
price_data: {
currency: 'eur',
product_data: {
name: 'T-shirt',
},
unit_amount: 2000,
},
quantity: 1,
}],
mode: 'payment',
success_url: 'https://example.com/success?session_id={CHECKOUT_SESSION_ID}',
cancel_url: 'https://example.com/cancel',
});
So, I'm trying the following.
to
function myFunction() {
var url = "https://api.stripe.com/v1/checkout/sessions";
var params = {
method: "post",
headers: {
Authorization:
"Basic " + Utilities.base64Encode("sk_test_4eC39HqLyjWDarjtT1zdp7dc:"),
},
payload: {
payment_method_types: ["card", "ideal"],
line_items: [
{
price_data: {
currency: "eur",
product_data: {
name: "T-shirt",
},
unit_amount: 2000,
},
quantity: 1,
},
],
mode: "payment",
success_url:
"https://example.com/success?session_id={CHECKOUT_SESSION_ID}",
cancel_url: "https://example.com/cancel",
},
};
var res = UrlFetchApp.fetch(url, params);
Logger.log(res.getContentText());
}
However, instead of getting the expected response object returned, I get the following error:
Exception: Request failed for https://api.stripe.com returned code 400. Truncated server response:
Log.error
{
error: {
message: "Invalid array",
param: "line_items",
type: "invalid_request_error",
},
}
What am I doing wrong? And how can I generalize the first example? What is the specific documentation I need that I'm not seeing?
Edit:
After stringifying the payload per the suggestion from the comments, now I get the following error:
Exception: Request failed for https://api.stripe.com returned code 400. Truncated server response:
Log.error
{
"error": {
"code": "parameter_unknown",
"doc_url": "https://stripe.com/docs/error-codes/parameter-unknown",
"message": "Received unknown parameter: {\"payment_method_types\":. Did you mean payment_method_types?",
"param": "{\"payment_method_types\":",
"type": "invalid_request_error"
}
}
I modified the script mentioned in the comments and now have a one that works for this purpose.
// [ BEGIN ] utilities library
/**
* Returns encoded form suitable for HTTP POST: x-www-urlformencoded
* #see code: https://gist.github.com/lastguest/1fd181a9c9db0550a847
* #see context: https://stackoverflow.com/a/63024022
* #param { Object } element a data object needing to be encoded
* #param { String } key not necessary for initial call, but used for recursive call
* #param { Object } result recursively populated return object
* #returns { Object } a stringified object
* #example
* `{
"cancel_url": "https://example.com/cancel",
"line_items[0][price_data][currency]": "eur",
"line_items[0][price_data][product_data][name]": "T-shirt",
"line_items[0][price_data][unit_amount]": "2000",
"line_items[0][quantity]": "1",
"mode": "payment",
"payment_method_types[0]": "card",
"payment_method_types[1]": "ideal",
"success_url": "https://example.com/success?session_id={CHECKOUT_SESSION_ID}"
}`
*/
const json2urlEncoded = ( element, key, result={}, ) => {
const OBJECT = 'object';
const typeOfElement = typeof( element );
if( typeOfElement === OBJECT ){
for ( const index in element ) {
const elementParam = element[ index ];
const keyParam = key ? `${ key }[${ index }]` : index;
json2urlEncoded( elementParam, keyParam, result, );
}
} else {
result[ key ] = element.toString();
}
return result;
}
// // test
// const json2urlEncoded_test = () => {
// const data = {
// time : +new Date,
// users : [
// { id: 100 , name: 'Alice' , } ,
// { id: 200 , name: 'Bob' , } ,
// { id: 300 , name: 'Charlie' , } ,
// ],
// };
// const test = json2urlEncoded( data, );
// // Logger.log( 'test\n%s', test, );
// return test;
// // Output:
// // users[0][id]=100&users[0][name]=Stefano&users[1][id]=200&users[1][name]=Lucia&users[2][id]=300&users[2][name]=Franco&time=1405014230183
// }
// // quokka
// const test = json2urlEncoded_test();
// const typeOfTest = typeof test;
// typeOfTest
// test
// [ END ] utilities library
From this question and this sample script, I thought that in this case, the values are required to be sent as the form data. So how about the following modification?
Modified script:
function myFunction() {
var url = "https://httpbin.org/anything";
var params = {
method: "post",
headers: {Authorization: "Basic " + Utilities.base64Encode("sk_test_4eC39HqLyjWDarjtT1zdp7dc:")},
payload: {
"cancel_url": "https://example.com/cancel",
"line_items[0][price_data][currency]": "eur",
"line_items[0][price_data][product_data][name]": "T-shirt",
"line_items[0][price_data][unit_amount]": "2000",
"line_items[0][quantity]": "1",
"mode": "payment",
"payment_method_types[0]": "card",
"payment_method_types[1]": "ideal",
"success_url": "https://example.com/success?session_id={CHECKOUT_SESSION_ID}"
}
};
var res = UrlFetchApp.fetch(url, params);
Logger.log(res.getContentText()); // or console.log(res.getContentText())
}
I think that point might be payment_method_types: ["card", "ideal"] is required to be sent as "payment_method_types[0]": "card" and "payment_method_types[1]": "ideal".
References:
Create a Session of official document
How to integrate Stripe payments with Google Apps Script

Sign with ethrereumjs-tx and send with HttpProvider gives "Exceeds block gas limit" regardless of gasLimit

I'm trying to write a server that holds private keys and signs transactions. I use ethereumjs-wallet/hdkey to generate accounts and private keys, ethereumjs-tx to sign transactions and web3js with a Httprovider to send transactions.
Unfortunately, when I try to send the transaction I always get the error message "Exceeds block gas limit" (even though I set my gasLimit to 21000, well below the block gas limit of my ganache-cli instance).
I suspect the raw encoded transaction is wrongly formed.
Any ideas what the actual problem is and how I can fix it?
Cheers
const hdkey = require('ethereumjs-wallet/hdkey');
const Transaction = require('ethereumjs-tx');
const walletHdpath = "m/44'/60'/0'/0/";
const hdwallet = hdkey.fromMasterSeed(bip39.mnemonicToSeed(process.env.KEYSTORE_SEED));
const web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
async function generateAccount() {
const wallet = hdwallet.derivePath(walletHdpath + nextAccountIndex).getWallet();
nextAccountIndex += 1;
const addr = '0x' + wallet.getAddress().toString('hex');
accounts[addr] = wallet;
await fundAccount(addr);
return addr;
}
async function fundAccount(address) {
const txParams = {
gasPrice: '20000000000',
gasLimit: '21000',
from: process.env.KEYSTORE_ADDRESS_0,
to: address,
value: web3.utils.toWei('0.1', 'ether'),
data: ''
}
const signed = signTransaction(txParams);
// this line throws exception: "exceeds block gas limit"
await web3.eth.sendSignedTransaction(signed.signed_transaction);
}
function signTransaction(txParams) {
const from = txParams.from.toLowerCase();
const wallet = accounts[from];
if (wallet === undefined) {
return {sucess: false, message: "unknown from account" }
}
const tx = new Transaction(txParams);
const pkey = wallet.getPrivateKey();
tx.sign(pkey);
const rawTx = '0x' + tx.serialize().toString('hex');
return { success: true, signed_transaction: rawTx }
}
The problem was that the values in the txParams need to be hex encoded and prefixed with 0x

Sending signed transactions to Ropsten

It's easy to use web3js to call functions that don't require signing (e.g. functions that do not update the state of a contract). However, it's not clear how to call functions that require signing, other than manually unlocking my MetaMask wallet and calling functions inside Remix environment.
After deploying my dapp for the first time to Ropsten, I need to call createItem(string name, uint price) 100 times to populate the items array initially. Since I don't want to do it manually in Remix, I want to write a script that does it automatically.
It looks like I need to have ethereumjs-tx in addition to web3js to sign transactions programatically without having MetaMask. I also need to have my account and privateKey. With all this information and the official web3js doc, I come up with the following:
// Call an external function programatically
const web3 = new Web3(new Web3.providers.HttpProvider("https://ropsten.infura.io"))
const account = "ACCOUNT_ADDRESS"
const privateKey = new Buffer('PRIVATE_KEY', 'hex')
const contract = new web3.eth.Contract(abi, CONTRACT_ADDRESS, {
from: account,
gas: 3000000,
})
const functionAbi = contract.methods.myFunctionName(myArgument).encodeABI()
let estimatedGas
contract.methods.myFunctionNAme(myArgument).estimateGas({
from: account,
}).then((gasAmount) => {
estimatedGas = gasAmount.toString(16)
})
const txParams = {
gasPrice: '0x' + estimatedGas,
to: CONTRACT_ADDRESS,
data: functionAbi,
from: account,
}
const tx = new Tx(txParams)
tx.sign(privateKey)
const serializedTx = tx.serialize()
web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex')).
on('receipt', console.log)
The code runs, but txParams is actually missing one key: nonce. When you run this, you get the following error:
Unhandled rejection Error: Returned error: nonce too low
Here are my questions:
Is this generally the right way to do what I am trying to do?
If 1 is true, how do I get the nonce parameter for a deployed contract?
References:
http://web3js.readthedocs.io/en/1.0/
https://github.com/ethereumjs/ethereumjs-tx
https://ethereum.stackexchange.com/questions/21402/web3-eth-call-how-can-i-set-data-param
https://ethereum.stackexchange.com/questions/6368/using-web3-to-sign-a-transaction-without-connecting-to-geth
UPDATE:
Thanks to Adam, now I learned how to get the nonce. So I added this following code:
let nonce
web3.eth.getTransactionCount(account).then(_nonce => {
nonce = _nonce.toString(16)
})
const txParams = {
gasPrice: '0x' + gasPrice,
to: CONTRACT_ADDRESS,
data: functionAbi,
from: account,
nonce: '0x' + nonce,
}
But now I keep running into this exception:
Unhandled rejection Error: Returned error: rlp: input string too long
for uint64, decoding into
(types.Transaction)(types.txdata).AccountNonce
Google search wasn't helpful except for letting me locate this file (https://github.com/ethereum/go-ethereum/blob/master/rlp/decode.go) that has the exception handler. Does anyone know how to solve this?
Generally looks correct. The only question I would have is how are you planning on loading the private key? You will either need to prompt for the private key, or import/read in the keystore and prompt for the password. You can use keythereum to accomplish this (See the key import section for example code).
The nonce is just an incremental number used to order transactions for an account. To get the correct value, simply use web3.eth.getTransactionCount(account)
EDIT - Example run using Ganache with locked accounts (--secure option):
SimpleContract.sol
pragma solidity ^0.4.19;
contract SimpleContract {
uint public val = 4;
function increment(uint amt) public {
val += amt;
}
function get() public constant returns (uint) {
return val;
}
}
test.js
const Web3 = require('web3');
const Tx = require('ethereumjs-tx');
const provider = new Web3.providers.HttpProvider("http://localhost:8545");
const web3 = new Web3(provider);
const account = '0x9a6d82ef3912d5ab60473124bccd2f2a640769d7'; // Ganache
const privateKey = Buffer.from('70f1384b24df3d2cdaca7974552ec28f055812ca5e4da7a0ccd0ac0f8a4a9b00', 'hex');
const contractAddress = '0x6dd7c1c13df7594c27e0d191fd8cc21efbfc98b4'; // Deployed manually
const abi = [{"constant":true,"inputs":[],"name":"val","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"get","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"amt","type":"uint256"}],"name":"increment","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}];
const contract = new web3.eth.Contract(abi, contractAddress, {
from: account,
gasLimit: 3000000,
});
const contractFunction = contract.methods.increment(3);
const functionAbi = contractFunction.encodeABI();
let estimatedGas;
let nonce;
console.log("Getting gas estimate");
contractFunction.estimateGas({from: account}).then((gasAmount) => {
estimatedGas = gasAmount.toString(16);
console.log("Estimated gas: " + estimatedGas);
web3.eth.getTransactionCount(account).then(_nonce => {
nonce = _nonce.toString(16);
console.log("Nonce: " + nonce);
const txParams = {
gasPrice: '0x09184e72a000',
gasLimit: 3000000,
to: contractAddress,
data: functionAbi,
from: account,
nonce: '0x' + nonce
};
const tx = new Tx(txParams);
tx.sign(privateKey);
const serializedTx = tx.serialize();
contract.methods.get().call().then(v => console.log("Value before increment: " + v));
web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex')).on('receipt', receipt => {
console.log(receipt);
contract.methods.get().call().then(v => console.log("Value after increment: " + v));
})
});
});
Results:
$ npm run my_test
> hello_world_dapp#1.0.0 my_test C:\cygwin\home\adamk\eth\hello_world_dapp
> node ./test.js
Getting gas estimate
Estimated gas: 6919
Nonce: 5
Value before increment: 19
{ transactionHash: '0xb6fdfc36cc32cb01a2be8832a387da586a44a37c1241bbf2979745536f206ed4',
transactionIndex: 0,
blockHash: '0xb6ee8d4e45585010d9a12d48aa37a478eb6021aad78599f1719cb424ab364bb5',
blockNumber: 10,
gasUsed: 26905,
cumulativeGasUsed: 26905,
contractAddress: null,
logs: [],
status: 1 }
Value after increment: 22
Here is a code-snippet for sending signed transaction on rinkeby.In a similar way,you can proceed for ropsten test network:
const Tx = require('ethereumjs-tx')
const Web3 = require('web3')
const web3 =new
Web3('https://rinkeby.infura.io/v3/9ce80a86c6c54d22aa821d0486a1a47d')
var account1 = '0xa00c70B72150D627cf53872eefD077079116B6a6'
var account2 = '0xD2a8aa318Fbc56995Db8C415BE6E40329DB1C56C'
const privateKey1 = Buffer.from(process.env.PRIVATE_KEY_1,'hex')
const privateKey2 = Buffer.from(process.env.PRIVATE_KEY_2,'hex')
web3.eth.getTransactionCount(account1,(err,txCount)=>{
const txObject = {
nonce:web3.utils.toHex(txCount),
to:account2,
value:web3.utils.toHex(web3.utils.toWei('0.1','ether')),
gasLimit:web3.utils.toHex(21000),
gasPrice:web3.utils.toHex(web3.utils.toWei('10','gwei')),
}
console.log(txObject)
const tx = new Tx(txObject)
tx.sign(privateKey1)
const serializedTransaction = tx.serialize()
const raw = '0x'+serializedTransaction.toString('hex')
web3.eth.sendSignedTransaction(raw,(err,txHash)=>{
console.log(txHash)
})
})

How to get the data of an ethereum block using geth

How can i get a block info from a running ethereum node using geth or nodejs or any other language? For example to get a block data from bitcoin, there is a config file which run a blocknotify.sh file when a transaction is confirmed and in that blocknotify.sh file there is this command : bitcoin-cli getblock "$#" >> "$#.json" which gets the block data then i can send a post request of that block data to an api. So i want to do the same thing that is to get the block data from ETH nodes and send a post request to an api when a transaction is confirmed. How can i do this ?
While running in geth console, you can use the web3 library to get block information:
> var blockNumber;
undefined
> var blockInfo;
undefined
> web3.eth.getBlockNumber(function(e, r) { blockNumber = r; });
undefined
> blockNumber;
2515149
> web3.eth.getBlock(blockNumber, function(e, r) { blockInfo = r; });
undefined
> blockInfo
{ difficulty: 1319089762, extraData: "0xd58301070d8650617269747986312e32332e30826c69", gasLimit: 4700036, gasUsed: 0, hash: "0xf9c495b5e5bcd3935aa4a6fd5a43009de29ca7d7be77d4b7cc4c68b8704bc422", logsBloom: "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", miner: "0x94cd009bbba97f30a36845e2025edf7544d62439", mixHash: "0xb8794a6d1b777f8c6fdf509f04896642f67dab82dc872ae9cbe9bcbf85172972", nonce: "0x264c013815697c2f", number: 2515149, parentHash: "0x0d2b4185aec34d8963b4c0b8fa7abb8604e1452bcb7f7f7d7a75a3d1cfd85f92", receiptsRoot: "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", sha3Uncles: "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347", size: 537, stateRoot: "0xc3810c2e763669a6e0219c78990c92b91c634d23810f4bd67144c4d76b9cfe6e", timestamp: 1516811780, totalDifficulty: 7642933628775356, transactions: [], transactionsRoot: "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", uncles: [] }
The web3 documentation can be found here: v0.2x.x, v1.0
EDIT - Example transaction info retreival:
> web3.eth.getTransaction('0xaebaf7e8207c417f6bb7920f3820e5220738d6825b6f577e3c3d0736d3c95b49', function(e, r) { if (e) console.log(e); else res = r; });
undefined
> res
{ blockHash: "0x0000000000000000000000000000000000000000000000000000000000000000", blockNumber: null, from: "0x0a78c28257b40d5076ea180bc6a9e4c597c5ea98", gas: 90000, gasPrice: 40000000000, hash: "0xaebaf7e8207c417f6bb7920f3820e5220738d6825b6f577e3c3d0736d3c95b49", input: "0x", nonce: 32, r: "0x902f7a7b7c3e4ebcab47014f9c3b81858cdc4b90ef36d9630adaf30b47ec370f", s: "0x6f09e7d66dc2146afa108322f433c12b629eadd149e1e113669b6bd2e0cd467e", to: "0xb8ac544e818d01a9533c9556d572d8366b91d6c1", transactionIndex: 0, v: "0x2a", value: 200000 }

Get specific data from a JSON object (Steam Api)

So I am practising some nodejs and this time I am playing around with steam api and json objects. But I am having some problems.
So, from the Steam api,
http://steamcommunity.com/profiles/<steamid>/inventory/json/730/2
I got the json from this code,
var request = require('request');
var url = "http://steamcommunity.com/profiles/<steamid>/inventory/json/730/2"
request({
url: url,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
var json = JSON.parse(body);
console.log(body)
}
});
And the json looks lite this, json-link
From the json I want to take out the classid and instanceid from each of the items, but there comes the problem. I don't know how. I know I need to parse it but nothing more unfortunately.
Would be very helpful if someone could explain how, or link a guide/tutorial so I can learn.
Thanks!
EDIT:
var request = require('request');
var _ = require('lodash');
var url = "http://steamcommunity.com/profiles/76561198007691048/inventory/json/730/2";
request({
url: url,
json: true
}, function jsonParse(error, response, data) {
console.log(data.rgDescriptions);
var item = getItems(data.rgDescriptions);
console.log(item);
}
);
function getItems(data){
var item = data;
if(!item){
return "error";
}
return _(item).keys().map(function(id){
return _.pick([id], "name");}).value();
Console give me this; [ {}, {}, {}, {}, {}, {}, {}, {},
{},.... ]
JSON look like this;
'1293508920_0':
{ appid: '730',
classid: '1293508920',
instanceid: '0',
icon_url: '-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXU5A1PIYQNqhpOSV-fRPasw8rsUFJ5KBFZv668FF4u1qubIW4Su4mzxYHbzqGtZ-KGlz8EuJcg3rnE9NiijVe3_UY-Zzr2JJjVLFEEeiQRtg',
icon_drag_url: '',
name: 'Shadow Case',
market_hash_name: 'Shadow Case',
market_name: 'Shadow Case',
name_color: 'D2D2D2',
background_color: '',
type: 'Base Grade Container',
tradable: 1,
marketable: 1,
commodity: 1,
market_tradable_restriction: '7',
},
'1644880589_236997301':
{ appid: '730',
classid: '1644880589',
instanceid: '236997301',
icon_url: '-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXU5A1PIYQNqhpOSV-fRPasw8rsUFJ4MAlVo6n3e1Y27OPafjBN09izq42ChfbzNvXTlGkD6p0lj7_FpNjx0VDj_UBoZ272cNfBdg48MAyB-VS3xum61Me_ot2XnqkB5QYc',
icon_drag_url: '',
name: 'MLG Columbus 2016 Mirage Souvenir Package',
market_hash_name: 'MLG Columbus 2016 Mirage Souvenir Package',
market_name: 'MLG Columbus 2016 Mirage Souvenir Package',
name_color: 'D2D2D2',
background_color: '',
type: 'Base Grade Container',
tradable: 1,
marketable: 1,
commodity: 0,
market_tradable_restriction: '7',
},
To work with complex objects or collections you can use lodash library.
So, you have json with the following format:
{
"success":true,
"rgInventory": {
"5719625206": {"id":"5719625206","classid":"1651313004","instanceid":"188530139","amount":"1","pos":1},
"5719034454": {"id":"5719034454","classid":"1649582636","instanceid":"188530139","amount":"1","pos":2},
"5718628709": {"id":"5718628709","classid":"1649582636","instanceid":"188530139","amount":"1","pos":3},
...
}
}
To extract array of required items, first of all install lodash library in your project: npm i -S, after that add this code into your file:
var _ = require('lodash');
function extractItems(data) {
var rgInventory = _.get(data, 'rgInventory');
if (!rgInventory) {
return [];
}
return _(rgInventory)
.keys()
.map(function(id) {
return _.pick(rgInventory[id], ['classid', 'instanceid']);
})
.value();
}