Digital Asset Node.js bindings: syntax for expressing 'time' type variable - node.js

I am working through the tutorial where it says how to create a contract.
Here is their code:
function createFirstPing() {
const request = {
commands: {
applicationId: 'PingPongApp',
workflowId: `Ping-${sender}`,
commandId: uuidv4(),
ledgerEffectiveTime: { seconds: 0, nanoseconds: 0 },
maximumRecordTime: { seconds: 5, nanoseconds: 0 },
party: sender,
list: [
{
create: {
templateId: PING,
arguments: {
fields: {
sender: { party: sender },
receiver: { party: receiver },
count: { int64: 0 }
}
}
}
}
]
}
};
client.commandClient.submitAndWait(request, (error, _) => {
if (error) throw error;
console.log(`Created Ping contract from ${sender} to ${receiver}.`);
});
}
I want to create a similar request for in my project that sends a field called 'datetime_added'. In my DAML code it is of type time. I cannot figure out the proper syntax for this request. For example:
arguments: {
fields: {
sender: { party: sender },
receiver: { party: receiver },
count: { int64: 0 },
datetime_added: { time: '2019 Feb 19 00 00 00' }
}
}
The format I am expressing the time is not what is causing the problem (although I acknowledge that it's also probably wrong). The error I'm seeing is the following:
Error: ! Validation error
▸ commands
▸ list
▸ 0
▸ create
▸ arguments
▸ fields
▸ datetime_added
✗ Unexpected key time found
at CommandClient.exports.SimpleReporter [as reporter] (/home/vantage/damlprojects/loaner_car/node_modules/#da/daml-ledger/lib/data/reporting/simple_reporter.js:36:12)
at Immediate.<anonymous> (/home/vantage/damlprojects/loaner_car/node_modules/#da/daml-ledger/lib/data/client/command_client.js:52:62)
at runCallback (timers.js:705:18)
at tryOnImmediate (timers.js:676:5)
at processImmediate (timers.js:658:5)
I don't understand, is time not a valid DAML data type?
Edit
I tried switching time to timestamp as follows
datetime_added: {timestamp: { seconds: 0, nanoseconds: 0 }}
causing the following error:
/home/......../damlprojects/car/node_modules/google-protobuf/google-protobuf.js:98
goog.string.splitLimit=function(a,b,c){a=a.split(b);for(var d=[];0<c&&a.length;)d.push(a.shift()),c--;a.length&&d.push(a.join(b));return d};goog.string.editDistance=function(a,b){var c=[],d=[];if(a==b)return 0;if(!a.length||!b.length)return Math.max(a.length,b.length);for(var e=0;e<b.length+1;e++)c[e]=e;for(e=0;e<a.length;e++){d[0]=e+1;for(var f=0;f<b.length;f++)d[f+1]=Math.min(d[f]+1,c[f+1]+1,c[f]+Number(a[e]!=b[f]));for(f=0;f<c.length;f++)c[f]=d[f]}return d[b.length]};goog.asserts={};goog.asserts.ENABLE_ASSERTS=goog.DEBUG;goog.asserts.AssertionError=function(a,b){b.unshift(a);goog.debug.Error.call(this,goog.string.subs.apply(null,b));b.shift();this.messagePattern=a};goog.inherits(goog.asserts.AssertionError,goog.debug.Error);goog.asserts.AssertionError.prototype.name="AssertionError";goog.asserts.DEFAULT_ERROR_HANDLER=function(a){throw a;};goog.asserts.errorHandler_=goog.asserts.DEFAULT_ERROR_HANDLER;
AssertionError: Assertion failed
at new goog.asserts.AssertionError (/home/vantage/damlprojects/loaner_car/node_modules/google-protobuf/google-protobuf.js:98:603)
at Object.goog.asserts.doAssertFailure_ (/home/vantage/damlprojects/loaner_car/node_modules/google-protobuf/google-protobuf.js:99:126)
at Object.goog.asserts.assert (/home/vantage/damlprojects/loaner_car/node_modules/google-protobuf/google-protobuf.js:99:385)
at jspb.BinaryWriter.writeSfixed64 (/home/vantage/damlprojects/loaner_car/node_modules/google-protobuf/google-protobuf.js:338:80)
at proto.com.digitalasset.ledger.api.v1.Value.serializeBinaryToWriter (/home/vantage/damlprojects/loaner_car/node_modules/#da/daml-ledger/lib/grpc/generated/com/digitalasset/ledger/api/v1/value_pb.js:289:12)
at jspb.BinaryWriter.writeMessage (/home/vantage/damlprojects/loaner_car/node_modules/google-protobuf/google-protobuf.js:341:342)
at proto.com.digitalasset.ledger.api.v1.RecordField.serializeBinaryToWriter (/home/vantage/damlprojects/loaner_car/node_modules/#da/daml-ledger/lib/grpc/generated/com/digitalasset/ledger/api/v1/value_pb.js:1024:12)
at jspb.BinaryWriter.writeRepeatedMessage (/home/vantage/damlprojects/loaner_car/node_modules/google-protobuf/google-protobuf.js:350:385)
at proto.com.digitalasset.ledger.api.v1.Record.serializeBinaryToWriter (/home/vantage/damlprojects/loaner_car/node_modules/#da/daml-ledger/lib/grpc/generated/com/digitalasset/ledger/api/v1/value_pb.js:822:12)
at jspb.BinaryWriter.writeMessage (/home/vantage/damlprojects/loaner_car/node_modules/google-protobuf/google-protobuf.js:341:342)
In short, I need to know what type to use in my Node.js client for a DAML value of type time and how to express it.

I would recommend using the reference documentation for the bindings (although, as of version 0.4.0, browsing through it to answer your question I noticed two mistakes). In the upper navigation bar of the page you can start from Classes > data.CommandClient and work your way down its only argument (SubmitAndWaitRequest) until, following the links to the different fields, you reach the documentation for the timestamp field, which, as the error suggests (despite the mistake in the documentation), should be a Timestamp, where seconds are expressed in epoch time (seconds since 1970).
Hence, to make the call you wanted this would be the shape of the object you ought to send:
arguments: {
fields: {
sender: { party: sender },
receiver: { party: receiver },
count: { int64: 0 }
datetime_added: { timestamp: { seconds: 0, nanoseconds: 0 } }
}
}
For your case in particular, I would probably make a small helper that uses the Date.parse function.
function parseTimestamp(string) {
return { seconds: Date.parse(string) / 1000, nanoseconds: 0 };
}
That you can then use to pass in the time you mentioned in the example you made:
arguments: {
fields: {
sender: { party: sender },
receiver: { party: receiver },
count: { int64: 0 }
datetime_added: { timestamp: parseTimestamp('2019-02-19') }
}
}
As a closing note, I'd like to add that the Node.js bindings ship with typing files that provide auto-completion and contextual help on compatible editors (like Visual Studio Code). Using those will probably help you. Since the bindings are written in TypeScript, the typings are guaranteed to be always up to date with the API. Note that for the time being, the auto-completion works for the Ledger API itself but won't give you help for arbitrary records that target your DAML model (the fields object in this case).

Related

AWS CDK: There can only be one default behavior across all sources

Background
I have a piece of cdk code that runs in a function. Each time through it creates a cloud front distribution. I want one instance to have a different value of behavior. This seems like a very simple thing, but I always get the error below that I do not understand.
Code
// 1. Default:
let behavior: cloudfront.Behavior = {isDefaultBehavior: true};
// Lambda Edge / Cloudfront Function Authentication...
if (subDomain == "monkey-ops") {
// 2. Cloudfront Function.
const cfFunct = new cloudfront.Function(this, 'id', {
functionName: 'http-auth-ops',
comment: 'http-auth for monkey-ops.monkeytronics.co.nz static site',
code: cloudfront.FunctionCode.fromFile({filePath: __dirname + '\\http-auth-ops-cf.js'})
});
behavior = {
isDefaultBehavior: false,
functionAssociations: [{
eventType: cloudfront.FunctionEventType.VIEWER_REQUEST,
function: cfFunct
}]
};
// behavior = {isDefaultBehavior: true};
} else {
behavior = {isDefaultBehavior: true};
}
let cloudFrontDistribution = new cloudfront.CloudFrontWebDistribution(this, subDomain + 'Distribution', {
originConfigs: [
{
customOriginSource: {
domainName: s3Bucket.bucketWebsiteDomainName,
originProtocolPolicy: cloudfront.OriginProtocolPolicy.HTTP_ONLY,
},
// behaviors : [ {isDefaultBehavior: true} ],
behaviors : [ behavior ],
}
],
viewerCertificate: cloudfront.ViewerCertificate.fromAcmCertificate(
tslCert,
{
aliases: [ subDomain + '.monkeytronics.co.nz' ],
// securityPolicy: cloudfront.SecurityPolicyProtocol.SSL_V3, // default
securityPolicy: cloudfront.SecurityPolicyProtocol.TLS_V1_2_2021,
sslMethod: cloudfront.SSLMethod.SNI, // default
},
),
});
Error
Gives the following error, which I can't unpick...
Error: There can only be one default behavior across all sources. [ One default behavior per distribution ].
at new CloudFrontWebDistribution (D:\MonkeySource\2-Cloud\cdk_stacks\node_modules\aws-cdk-lib\aws-cloudfront\lib\web-distribution.js:1:6631)
at new StaticSite (D:\MonkeySource\2-Cloud\cdk_stacks\lib\factory\static-site\static-site-factory.ts:120:42)
at new SnWebStack (D:\MonkeySource\2-Cloud\cdk_stacks\lib\sn-web-stack.ts:57:7)
at Object.<anonymous> (D:\MonkeySource\2-Cloud\cdk_stacks\bin\cdk.ts:19:1)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Module.m._compile (D:\MonkeySource\2-Cloud\cdk_stacks\node_modules\ts-node\src\index.ts:1056:23)
at Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Object.require.extensions.<computed> [as .ts] (D:\MonkeySource\2-Cloud\cdk_stacks\node_modules\ts-node\src\index.ts:1059:12)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
Subprocess exited with error 1
The error message is misleading. You are getting it because you have no default behavior configured.
{
isDefaultBehavior: true, // <-- This needs to be true for one behavior
functionAssociations: [{
eventType: cloudfront.FunctionEventType.VIEWER_REQUEST,
function: cfFunct
}]
}
It means that you need to have only single default behavior.
But you can add multiple behaviors.
Cloudfront let's you create multiple behaviors and origins, which then can be used for multiple purposes.
Check the examples here
https://kuchbhilearning.blogspot.com/2022/10/add-cloudfront-behavior-and-origin.html
https://kuchbhilearning.blogspot.com/2022/10/api-gateway-and-cloud-front-in-same.html

Trying to fetch spot price using uniswap SDK but transaction is throwing error LOK?

const quotedAmountOut = await quoterContract.callStatic.quoteExactInputSingle(
immutables.token0,
immutables.token1,
immutables.fee,
amountIn,
0
)
I created two erc20 dummy tokens and created a pool for them using uniswapV3Factory createPool() method and obtained the pool address. But when I wanted to fetch the spot price for the tokens i have used using the above script it is throwing following Error:
Error: call revert exception; VM Exception while processing transaction: reverted with reason string "LOK" [ See: https://links.ethers.org/v5-errors-CALL_EXCEPTION ] (method="quoteExactInputSingle(address,address,uint24,uint256,uint160)", data="0x08c379a0000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000034c4f4b0000000000000000000000000000000000000000000000000000000000", errorArgs=["LOK"], errorName="Error", errorSignature="Error(string)", reason="LOK", code=CALL_EXCEPTION, version=abi/5.7.0)
at Logger.makeError (/Users/apple/Desktop/solidity/deploy/node_modules/#ethersproject/contracts/lib/index.js:20:58)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
reason: 'LOK',
code: 'CALL_EXCEPTION',
method: 'quoteExactInputSingle(address,address,uint24,uint256,uint160)',
data: '0x08c379a0000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000034c4f4b0000000000000000000000000000000000000000000000000000000000',
errorArgs: [ 'LOK' ],
errorName: 'Error',
errorSignature: 'Error(string)',
address: '0xb27308f9F90D607463bb33eA1BeBb41C27CE5AB6',
args: [
'<Token-1-Address>',
'<Token-2-Address>',
500,
BigNumber { _hex: '0x0de0b6b3a7640000', _isBigNumber: true },
0
],
transaction: {
data: '0xf7729d4300000000000000000000000008a2e53a8ddd2dd1d895c18928fc63778d97a55a0000000000000000000000006d7a02e23505a74143199abb5fb07e6ea20c6d6300000000000000000000000000000000000000000000000000000000000001f40000000000000000000000000000000000000000000000000de0b6b3a76400000000000000000000000000000000000000000000000000000000000000000000',
to: '0xb27308f9F90D607463bb33eA1BeBb41C27CE5AB6'
}
}
i found the issue here is your token address you provided, like token0 is WETH9 you must provide the exactly WETH9 token address, you can find it on etherscan.io

Trouble generating an Intent with delegateDirective from a TouchEvent handler (Alexa)

I need to confirm deleting a task from a button event. For this reason, I want Alexa to ask for confirmation, and therefore I need to generate a DeleteTaskIntent from my code.
I have tried this:
return handlerInput.responseBuilder.addDelegateDirective({
name: 'DeleteTaskIntent',
confirmationStatus: 'NONE',
slots: {
idTask:{
name: 'idTask',
value: idTask,
confirmationStatus: 'NONE'
}
}
}).getResponse();
In my TouchEventHandler, but after checking the request in the requestEnvelope, I see this:
request: {
type: 'System.ExceptionEncountered',
requestId: 'amzn1.echo-api.request.9c2cf5f4-2f2c-419c-898c-05bd5f096810',
timestamp: '2022-02-23T11:30:08Z',
locale: 'es-ES',
error: {
type: 'INVALID_RESPONSE',
message: 'Directive "Dialog.Delegate" cannot be used in response to an event'
},
cause: {
requestId: 'amzn1.echo-api.request.0494d80d-c6ac-41d6-b3a2-dffd97f427b5'
}
}
And the error
{
"name": "AskSdk.GenericRequestDispatcher Error"
}
also appears, which suggests that no handler can handle this case.
Any idea about what I'm doing wrong when trying to generate the Intent?

Error when trying to use CanvasJS via RequireJS

I'm trying to use CanvasJS inside my project. I'm using RequireJS to manage the modules, and have this in the main script:
define(['domReady',"canvasjs","common-functions"], function(domReady,CanvasJS) {
domReady(function () {
window.CanvasJS = CanvasJS;
init_page_select();
});
});
This is what I have in my requireJS config file for the path:
"paths": {
// other stuff here
"canvasjs": "node_modules/canvasjs/dist/canvasjs.min"
},
I can see the canvasjs.min.js file being grabbed fine - but then I get this weird error:
ReferenceError: intToHexColorString is not defined[Learn More] canvasjs.min.js:7:7042
[33]</n.prototype.render https://www.test.org/2018/js/lib/node_modules/canvasjs/dist/canvasjs.min.js:7:7042
[28]</n.prototype.render https://www.test.org/2018/js/lib/node_modules/canvasjs/dist/canvasjs.min.js:5:14150
n/this.render https://www.test.org/2018/js/lib/node_modules/canvasjs/dist/canvasjs.min.js:8:17771
init_page_select https://www.test.org/2018/js/lib/spot_view_stats.js:83:2
<anonymous> https://www.test.org/2018/js/lib/spot_view_stats.js:4:3
domReady https://www.test.org/2018/js/lib/domready.js:105:13
<anonymous> https://www.test.org/2018/js/lib/spot_view_stats.js:2:2
execCb https://www.test.org/2018/js/lib/require.js:5:12859
check https://www.test.org/2018/js/lib/require.js:5:6575
enable/</< https://www.test.org/2018/js/lib/require.js:5:9031
bind/< https://www.test.org/2018/js/lib/require.js:5:812
emit/< https://www.test.org/2018/js/lib/require.js:5:9497
each https://www.test.org/2018/js/lib/require.js:5:289
emit https://www.test.org/2018/js/lib/require.js:5:9465
check https://www.test.org/2018/js/lib/require.js:5:7169
enable/</< https://www.test.org/2018/js/lib/require.js:5:9031
bind/< https://www.test.org/2018/js/lib/require.js:5:812
emit/< https://www.test.org/2018/js/lib/require.js:5:9497
each https://www.test.org/2018/js/lib/require.js:5:289
emit https://www.test.org/2018/js/lib/require.js:5:9465
check https://www.test.org/2018/js/lib/require.js:5:7169
enable https://www.test.org/2018/js/lib/require.js:5:9358
init https://www.test.org/2018/js/lib/require.js:5:5716
h https://www.test.org/2018/js/lib/require.js:5:4287
completeLoad https://www.test.org/2018/js/lib/require.js:5:12090
onScriptLoad https://www.test.org/2018/js/lib/require.js:5:13014
I'm invoking it with:
var chart = new CanvasJS.Chart("thegraph",
{
title:{
text: impressionText
},
theme: "theme2",
axisX: {
valueFormatString: "MMM-DD-YYYY",
labelAngle: -50
},
axisY:{
valueFormatString: "#0",
title: impressionText
},
data: [
{
type: "line",
showInLegend: true,
legendText: legendText,
dataPoints: dataPoints
}
]
});
chart.render();
Interestingly, if I tell it to load canvasjs.js instead of canvasjs.min.js, I get another error:
ReferenceError: intToHexColorString is not defined[Learn More]
OK so the problem seemed to be my version. For some reason "npm install canvasjs" was installing 1.8.1, but 2.2 was out. As per their request, I updated it to 2.2 and it sorted the problem. It seems weird npm is running such an outdated version though

How to use realm on an electron app?

ERROR in ./~/realm/lib/browser/index.js
Module not found: Error: Can't resolve 'react-native' in
'/Users/H/Documents/MyApp/node_modules/realm/lib/browser'
# ./~/realm/lib/browser/index.js 21:0-45
# ./~/realm/lib/index.js
# ./render/routes/tools/Network.js
# ./render/router.js
# ./render/index.js
# multi (webpack)-dev-server/client?http://localhost:9527 webpack/hot/dev-server react-hot-loader/patch webpack-dev-server/client?http://localhost:9527/ webpack/hot/only-dev-server ./render/index.js
Not rewriting GET /dist/bundle.js because the path includes a dot (.) character.
I want to use realm in an electron app, and I used the code below but it doesn't work and the error imformation is above.
const Realm = require('realm')
let realm = new Realm({
schema: [
{
name: 'LogItem',
properties: {
time: 'date',
percent: 'double'
}
}
]
})
realm.write(() => {
realm.create('Log', {
time: new Date(),
percent: 90.00
})
})
Realm is working on Electron support, but it's not supported currently (which is why you're getting errors). You can keep track of their efforts here: https://github.com/realm/realm-js/issues/818

Resources