How to get TransactionUnspentOutput as a hex encoded bytes string programmatically - node.js

So basically I want to convert a normal UTxO hash like:
550665309dee7e2f64d13f999297f001763f65fe50bb05524afc0990c7dce0c3
to a TransactionUnspentOutput as a hex encoded bytes string like:
828258205537396d59c1b0546bb9cec5cb6b930238af2d8998d24ca1d47e89a3dd400a8701825839016af9a0d2c9b5bce8999bc6430eb48f424399b73f0ecc143f40e8cac89b130cc3198a8594862fe25df331cb79447304dcd49712c86834fdf1821a00150bd0a1581cb0df0ee7dbb96b18b682a1091514f250eb0ec1122e6c4bf3b4d45123a14b436f6e766963743033363701
This is how it is done with a nami wallet implementation:
cardano.getUtxos(amount?: Value, paginate?: {page: number, limit: number}) : [TransactionUnspentOutput]
I tried to pass a UTxO into the lucid utxoToCore() function:
export const utxoToCore = (utxo: UTxO): Core.TransactionUnspentOutput => {
const output = C.TransactionOutput.new(
C.Address.from_bech32(utxo.address),
assetsToValue(utxo.assets)
);
if (utxo.datumHash) {
output.set_datum(
C.Datum.new_data_hash(C.DataHash.from_bytes(fromHex(utxo.datumHash)))
);
}
return C.TransactionUnspentOutput.new(
C.TransactionInput.new(
C.TransactionHash.from_bytes(fromHex(utxo.txHash)),
C.BigNum.from_str(utxo.outputIndex.toString())
),
output
);
};
However the only output I get is:
TransactionUnspentOutput { ptr: 1247376 }
How to get the unpacked (?), or at least the right format I want, TransactionUnspentOutput?

It looks like you are trying to call an external library. Usually, in such cases, it will return you a memory address. Just like you have it in wasm calls through browser client. One way is to deserialize your object inside your node js code.
Maybe you can use some sorta utility function to get it as a string.
E.g. https://github.com/Emurgo/cardano-serialization-lib/blob/master/doc/getting-started/metadata.md#json-conversion
Hope this helps

Related

What is difference between get data from file and after parse data in byte?

I have some problems with the length in a byte of data get from a file. In my case, I use the readFileSync method to get data from a text file. But when I do something like the below code. It gives me 2 difference results.
let data = fs.readFileSync('size.txt');
console.log(data.length);
console.log(JSON.stringify(JSON.parse(data)).length);
Result in: 579859 (console log 1) and 409065 (console log 2)
So, I don't understand why the size is decreased after I parsed it to JSON and then I use the stringify method.
Thank you for any helping!
JSON.stringify will not restore the spaces like in the below example :
const obj = `{
"keyA": "obiwan kenobi",
"testB": "foo"
}`;
console.log(obj);
const obj2 = JSON.stringify(JSON.parse(obj));
console.log(obj.length, obj2.length);
console.log(obj2);

Find JSON value using variable from function

I'm working on a function where I need to be able to input a string which is a key in a JSON object then I need to be able to take the actual object and tack on the string to get the correct value from the JSON
function contact(contact_method) {
let method = array[place].settings.contact_method; // Example for contact_method is 'first_contact_method'
console.log(method)
}
The idea is I have 3 different contact methods and I'd like to be able to use the same function for all 3. I know the code above is barely a function but I think it shows what I want to be able to do.
I could not find anything on MDN or SO about this. I had tried using ES6 and string with `` but that did not work it just returned [object Object].first_contact_method
You can access keys of objects with a variable by using [].
For instance:
const obj = { a: 4, b: 5, c: () => { /* do something*/}, d() { /* do something*/ } }
const keyA = 'a'
const keyC = 'c'
const valueA = obj[keyA] // valueA === 4
const methodC = obj[keyC]
// Call method c
methodC()
// or short
obj[keyC]()
// and even for "real" methods
obj['d']()

nodejs bodyParser.json convert float number

My request postman request
{
"data":{
"hoauBagId":"WEB20180904003",
"battery":null,
"incoterm":30.0,
}
}
But when I do console req.body
{ data:
{ hoauBagId: 'WEB20180904003',
battery: null,
incoterm: 30,
}
}
I know the problem because I use "app.use(bodyParser.json());" and it convert my number
How can I get 30.0 instead of 30?
You can parse it to float parseFloat() explicitly.
I think this happens only because 30.0 = 30! Please try with 30.1 I think should be satisfied with your result
You can done this with parseFloat()
Lets say you create a function that return a float number like:
function pFloat(data) {
return parseFloat(data);
}
Where data is a new variable that you create from response data like:
const data = data.incoterm
or you could simply:
var data = parseFloat(data.incoterm);

how does mongo determine how to serialize an object?

I'm working with a BigNumbers from the bignumber.js package
I'm new to Mongo and I'm curious as to how Mongo knows how to serialize this object correctly (or any other object for that matter)?
I ask because I have 2 scripts which are seemingly identical in they way the insert these objects, but in one script the BigNumbers are inserted as strings in the other script they are inserted as numbers.
The object comes in from an any stream and I need to convert or cast the any object to Altitude.
Sample code:
export interface Altitude {
altitude: BigNumber;
minAltitude: BigNumber;
maxAltitude: BigNumber;
}
... 'message' object of type any from stream ...
// this JSON back and forth stuff seems like it should be unnecessary
let jsonString = JSON.stringify(message);
let alt = JSON.parse(jsonString) as Altitude;
collection.insert(alt, (error: MongoError, result: InsertOneWriteOpResult) => {
...
});
Strings are inserted for the BigNumbers.
Seeing the values being inserted into Mongo as strings I try forcing the issue even more, just to see if it would work:
let alt = JSON.parse(jsonString) as Altitude;
let alt1 = {
size: alt.altitude as BigNumber,
minAltitude: alt.minAltitude as BigNumber,
maxAltitude: alt.minAltitude as BigNumber,
};
collection.insert(alt1, (error: MongoError, result: InsertOneWriteOpResult) => {
...
});
However the values are still inserted as strings. And in my other script everything is numbers.
Ideas?
MongoDB uses BSON Serialisation. The actual implementation would depend on the driver.
Reference https://www.mongodb.com/json-and-bson

Internet Explorer truncating flashVars containing JSON

This only happens in IE.
I'm using swfobject and loading the flash vars as such
var flashVars = {
myVar:'{"url":"http://google.com/", "id":"9999"}',
};
var params = {
allowFullScreen:"true",
wmode:"transparent",
allowScriptAccess:'always'
};
swfobject.embedSWF("mySwf.swf", "mySwf", "512", "318", "10.0.0", "./js/swfobject/expressInstall.swf", flashVars, params);
Everything works perfectly in all browser but IE. I checked myVar and it comes into the swf as { and that's it. I know it's dying at the '. I've tried putting a \ infront, then tried \\ and kept adding one slash until I got to \\\\\\\\. I even inverted all the slashes and tried the same ritual. Nothing.
I can get the string to finally come through, with inverted quotes and using double slashes, but then my JSON parser gets mad about there being slashes in my string.
Here's an example of what works, but of what is invalid JSON:
"{\\'url\\':\\'http://google.com/\\', \\'id\\':\\'9999\\'}"
Yep IE treats flashVars differently to all the other major browsers, I believe you need to make use of the JavaScript encodeURIComponent method which will escape all reserved characters from your String, eg:
// Removing all reserved characters from the flashVar value.
var flashVars = {
myVar: encodeURIComponent('{"url":"http://google.com/", "id":"9999"}'),
};
If you are passing multiple values in the flashVars then you could iterate through them and encode all chars in a single pass:
var flashVars = {
myVar: '{"url":"http://google.com/", "id":"9999"}',
anotherVar: 42
};
// Escape all values contained in the flashVars object.
for (key in flashVars) {
if (flashVars.hasOwnProperty(key)) {
flashVars[key] = encodeURIComponent(flashVars[key]);
}
}
As #dgmdan and #bcmoney suggested, it would probably make your code easier to read if you made use of JSON.stringify - however, you need to bear in mind that IE8 and below do not have a native JSON object, so you will need to include Crockford's JS Library in your HTML page.
// Making use of a JSON library.
var flashVars = {
myVar: encodeURIComponent(JSON.stringify({ url: "http://google.com/", id: "9999"})),
};
Also, it's worth bearing in mind that flashVars are limited to ~64k; so if you are planning to pass a lot of data, it might be better to use an ExternalInterface call to pull them from the JavaScript instead.
Try this to replace your first 3 lines:
var subVars = { url: "http://google.com/", id: "9999" };
var flashVars = { myVar: JSON.stringify(subVars) };

Resources