Corda - Redeem Tokens - Token SDK + Accounts - token

I'm trying to use the token SDK for the first time and I am not being able to redeem the correct amount of tokens from a specific Corda account.
How I am issuing the tokens:
val accountInfo = accountService.accountInfo(accountId)
val accountKey = subFlow(RequestKeyForAccountFlow(accountInfo.state.data,initiateFlow(ourIdentity)))
val tokens = 10 of MyTokenType issuedBy ourIdentity heldBy accountKey
subFlow(IssueTokens(listOf(tokens), emptyList()))
I also implemented the function report() to Query the Vault to GET the amount of tokens for each account:
fun report (accountInfo: StateAndRef<AccountInfo>) : Amount<TokenType> {
val criteria = QueryCriteria.VaultQueryCriteria(
status = Vault.StateStatus.UNCONSUMED,
relevancyStatus = Vault.RelevancyStatus.RELEVANT,
externalIds = listOf (accountInfo.state.data.identifier.id)
)
val exprAggregate=
builder {
com.r3.corda.lib.tokens.contracts.internal.schemas.PersistentFungibleToken::amount.sum()
}
val aggregateCriteria =
QueryCriteria.VaultCustomQueryCriteria(exprAggregate)
val otherResult = serviceHub.vaultService.queryBy(
criteria = criteria.and(aggregateCriteria),
contractStateType = FungibleToken::class.java).otherResults[0]
val sum= if (otherResult == null) 0 else (otherResult as Long)
return sum.MyToken
If I issue 10 tokens for a specific account I receive this on the GET that calls my report function:
{
"value": {
"quantity": 10,
"displayTokenSize": 1,
"token": {
"tokenIdentifier": "MyToken",
"fractionDigits": 0,
"displayTokenSize": 1,
"customTokenType": false,
"regularTokenType": true,
"tokenClass": "com.r3.corda.lib.tokens.contracts.types.TokenType",
"pointer": false
}
},
"message": "Tokens in account."
}
This shows me that I am actually Issuing the tokens right, since the quantity of tokens is the 10 tokens that I just issued.
What I am doing in the Redeem flow:
val accountInfo = accountService.accountInfo(accountId)
val tokens: Amount<TokenType> = 10.MyToken
val heldByAccount: QueryCriteria = QueryCriteria.VaultQueryCriteria()
.withExternalIds(Collections.singletonList(accountInfo.state.data.identifier.id))
subFlow(RedeemFungibleTokens(amount = tokens, issuer = ourIdentity, observers = emptyList(), queryCriteria = heldByAccount))
But When I do the GET to run my report() functin it just gives me this as a response:
{
"value": {
"quantity": 0,
"displayTokenSize": 1,
"token": {
"tokenIdentifier": "MyToken",
"fractionDigits": 0,
"displayTokenSize": 1,
"customTokenType": false,
"regularTokenType": true,
"tokenClass": "com.r3.corda.lib.tokens.contracts.types.TokenType",
"pointer": false
}
},
"message": "Tokens in account."
}
This shows me that my Redeem flow it's not working because it is not only redeeming 10 tokens but all the tokens for that account, since the quantity is equals to zero.
Any ideas on how I can fix this?
Thanks a lot

I believe the answer is add a changeHolder to the RedeemFungibleTokens sub-flow you are calling.
Take a look at:
https://training.corda.net/libraries/accounts-exercise/

Related

How do I use information from Roblox Games API?

So I am trying to make some code that gets information about games using the Roblox API. I do get data back when I send a request, but I can't figure out a way to use the data in the code. Because when I decode it, it looks like this:
{
["data"] = ▼ {
[1] = ▼ {
["allowedGearCategories"] = {},
["allowedGearGenres"] = ▶ {...},
["copyingAllowed"] = false,
["createVipServersAllowed"] = false,
["created"] = <creation date>,
["creator"] = ▶ {...},
["description"] = "",
["favoritedCount"] = 0,
["genre"] = "Comedy",
["id"] = <the id>,
["isAllGenre"] = false,
["isFavoritedByUser"] = false,
["isGenreEnforced"] = true,
["maxPlayers"] = 10,
["name"] = <the name>,
["playing"] = 0,
["rootPlaceId"] = <the id>,
["studioAccessToApisAllowed"] = false,
["universeAvatarType"] = "PlayerChoice",
["updated"] = <update date>,
["visits"] = 0
}
}
}
I censored some of the information about which game it is, but that information isn't important here. The important thing is that it says "1" under "data", and if I type that into the code, it uses it as a number. So I can't access anything further down in the list than "data".
Here is my code, if it helps:
local universe = Proxy:Get("https://api.roblox.com/universes/get-universe-containing-place?placeid="..placeId).body
local universeDecoded = http:JSONDecode(universe)
local universeId = universeDecoded.UniverseId
local placeInfo = http:JSONDecode(Proxy:Get("https://games.roblox.com/v1/games?universeIds="..universeId).body)
print(placeInfo.data)
Also, sorry for not knowing a lot of programming words, so I say stuff like "further down in the list". But I hope it's clear what I mean.
I figured it out myself. I just had to write
print(placeInfo.data[1])

How to properly build a Clio Power Query custom connector for Power BI?

I am building a custom Power Query connector for Clio. It is my first PQ custom connector so I need to know 2 things:
How do I work in the token handling in the Token Handling section?
Once I get that working, how do I make the Client ID and Secret a dynamic reference to a separate file? I don't like the idea of hardcoding that into something.
Here is my code:
section Clio;
[DataSource.Kind="Clio", Publish="Clio.Publish"]
shared Clio.Contents = (optional message as text) =>
let
_message = if (message <> null) then message else "(no message)",
a = "Hello from Clio: " & _message
in
a;
OAuthBaseUrl = "https://app.clio.com/api/v4";
// Data Source Kind description
Clio = [
Authentication = [
OAuth = [
StartLogin = StartLogin,
FinishLogin = FinishLogin
]
],
Label = Extension.LoadString("DataSourceLabel")
];
// Data Source UI publishing description
Clio.Publish = [
Beta = true,
Category = "Other",
ButtonText = { Extension.LoadString("ButtonTitle"), Extension.LoadString("ButtonHelp") },
LearnMoreUrl = "https://powerbi.microsoft.com/",
SourceImage = Clio.Icons,
SourceTypeImage = Clio.Icons
];
StartLogin = (resourceUrl, state, display) =>
let
AuthorizeUrl = OAuthBaseUrl & "/oauth/authorize?" & Uri.BuildQueryString([
response_type = "code",
client_id = client_id_code,
redirect_uri = "https://app.clio.com/oauth/approval",
state = state
])
in
[
LoginUri = "https://app.clio.com",
CallbackUri = "https://app.clio.com/oauth/approval",
WindowHeight = 1080,
WindowWidth = 720
];
FinishLogin = (context, callbackUri, state) =>
let
Parts = Uri.Parts(callbackUri)[Query]
in
TokenMethod(Parts[code], "authorization_code", context);
//Token Handling
TokenMethod = (grant_type, optional verifier) =>
let
query = [
client_id = client_id_code,
client_secret = client_secret_code,
grant_type = "refresh_token",
refresh_token = I_don't_know_what_to_put_here
],
ManualHandlingStatusCodes= {400,403},
Response = Web.Contents(OAuthBaseUrl & "/token", [
Content = Text.ToBinary(Uri.BuildQueryString(query)),
Headers = [
#"Content-type" = "application/x-www-form-urlencoded",
#"Accept" = "application/json"
],
ManualStatusHandling = ManualHandlingStatusCodes
]),
Parts = Json.Document(Response)
in
// check for error in response
if (Parts[error]? <> null) then
error Error.Record(Parts[error], Parts[message]?)
else
Parts;
Refresh = (resourceUrl, refresh_token) => TokenMethod(refresh_token, "refresh_token");
Clio.Icons = [
Icon16 = { Extension.Contents("Clio16.png"), Extension.Contents("Clio20.png"), Extension.Contents("Clio24.png"), Extension.Contents("Clio32.png") },
Icon32 = { Extension.Contents("Clio32.png"), Extension.Contents("Clio40.png"), Extension.Contents("Clio48.png"), Extension.Contents("Clio64.png") }
];

Metric math alarms: How can I use a for_each expression to loop over metrics within a dynamic block?

I am trying to create dynamic metric math alarms, that are configurable with a JSON.
I am struggling with looping over the metric alarm with a for_each expression as this is a loop within a loop.
Here is an example of what I am trying to do:
resource "aws_cloudwatch_metric_alarm" "Percentage_Alert" {
for_each = var.percentage_error_details
locals { alarm_details = each.value }
alarm_name = "${terraform.workspace}-${each.key}"
comparison_operator = local.alarm_details["Comparison_Operator"]
evaluation_periods = "1"
threshold = local.alarm_details["Threshold"]
metric_query {
id = "e1"
expression = local.alarm_details["Expression"]
label = local.alarm_details["Label"]
return_data = "true"
}
dynamic "metric_query" {
for metric in each.value["Metrics"]{
id = metric.key
metric_name = metric.value
period = local.alarm_details["Period"]
stat = local.alarm_details["Statistic"]
namespace = local.full_namespace
unit = "Count"
}
}
}
And this is the sample JSON
{
"locals": {
"Name": {
"Name": "metric_math",
"Metrics": {
"m1": "Sucess",
"m2": "Failure"
},
"Expression": "100*(m2/(m1+m2))",
"Threshold" : 1,
"Period": 25,
"Priority": "critical",
"Statistic": "Sum",
"Label": "label",
"Comparison_Operator": "GreaterThanOrEqualToThreshold"
}
}
}
And this is the error message i'm getting:
Error: Invalid block definition
On ../modules/cloudwatch/metriclogfilter/main.tf line 89: Either a quoted
string block label or an opening brace ("{") is expected here.
Any help would be much appreciated.

Rate limit exceeded in tweepy

I faced with a limitation problem using tweepy. I am recieving Rate limit exceeded error every time running script. I need to know is there any way to know how many requests may I do before Rate limit exceeded error occured.
Tweepy offers access to the Rate Limit API.
From their documentation
import tweepy
consumer_key = 'a'
consumer_secret = 'b'
access_token = 'c'
access_token_secret = 'd'
# OAuth process, using the keys and tokens
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
# Creation of the actual interface, using authentication
api = tweepy.API(auth)
# Show the rate Limits
print api.rate_limit_status()
You'll then see a list of all the available rate limits and how many calls you have remaining.
For example:
{ "rate_limit_context" : { "access_token" : "1234" },
"resources" : { "account" : { "/account/login_verification_enrollment" : { "limit" : 15,
"remaining" : 15,
"reset" : 1411295469
},
"/account/settings" : { "limit" : 15,
"remaining" : 15,
"reset" : 1411295469
},
"/account/update_profile" : { "limit" : 15,
"remaining" : 15,
"reset" : 1411295469
},
"/account/verify_credentials" : { "limit" : 15,
"remaining" : 15,
"reset" : 1411295469
}
The rate limits can be found in the Twitter API documentation:
https://dev.twitter.com/docs/rate-limiting/1#rest

Create Checks with Quickbooks API

Please help me on writing a check using the QuickBooks online(Qbo) API. I tried to do that but i'm always getting an error saying "Error validating Detail Lines:At least one detail line is required." Sample Code is in Below.. How should I add Lines for Checks.
Dim existingChk = New Qbo.Check()
Dim existingChks = commonService.FindAll(existingChk, 1, 10).ToList()
Dim payment = New Qbo.Payment()
Dim payments = commonService.FindAll(payment, 1, 10).ToList()
Dim qboCheck = New Intuit.Ipp.Data.Qbo.CheckHeader()
Dim bank = New Intuit.Ipp.Data.Qbo.Account()
bank.Type = Intuit.Ipp.Data.Qbo.AccountTypeEnum.Asset
Dim Banks = commonService.FindAll(bank, 1, 100).ToList()
Dim accountId As New Qbo.IdType
For Each bnk As Intuit.Ipp.Data.Qbo.Account In Banks
If bnk.Name = "Test Bank" Then
accountId = bnk.Id
End If
Next
qboCheck.BankAccountId = accountId
qboCheck.BankAccountName = "Test Bank"
qboCheck.TotalAmt = 20.0
qboCheck.Currency = Intuit.Ipp.Data.Qbo.currencyCode.USD
qboCheck.TxnId = payments(0).Id
Dim qboCustomer = New Intuit.Ipp.Data.Qbo.Customer()
Dim qboCustomers = commonService.FindAll(qboCustomer, 1, 10).ToList()
For Each cus As Intuit.Ipp.Data.Qbo.Customer In qboCustomers
If cus.Name.Contains("Customer1") Then
qboCheck.EntityId = cus.Id
End If
Next
qboCheck.EntityType = Qbo.EntityTypeEnum.Customer
Dim check = New Intuit.Ipp.Data.Qbo.Check()
check.Header = qboCheck
check.Id = New Qbo.IdType
check.Id.idDomain = existingChks(0).Id.idDomain
check.Id.Value = CInt(existingChks(0).Id.Value) + 1
Dim resultCheck As Qbo.Check = TryCast(commonService.Add(check), Qbo.Check)
Looks like it is a bug in .net devkit(I'm not 100% sure).
JavaDocs says accountId and itemId both are inherited from LinePurchase(PFB snapshot). But in .net devkit, I don't see those fields neither in LinePurchase nor in LineBase.
JavaDoc Ref - http://developer-static.intuit.com/SDKDocs/QBV2Doc/ipp-java-devkit-2.0.10-SNAPSHOT-javadoc/
API endpoints are working fine.
https://developer.intuit.com/docs/0025_quickbooksapi/0050_data_services/v2/0400_quickbooks_online/check#Sample_Create_Request_XML
<?xml version="1.0" encoding="utf-8" ?>
<Check xmlns:ns2="http://www.intuit.com/sb/cdm/qbo" xmlns="http://www.intuit.com/sb/cdm/v2">
<Header>
<TxnDate>2013-08-09</TxnDate>
<BankAccountId>44</BankAccountId>
<EntityId>2</EntityId>
</Header>
<Line>
<Desc>Hard Disks</Desc>
<Amount>500</Amount>
<BillableStatus>NotBillable</BillableStatus>
<ItemId>4</ItemId>
<Qty>10</Qty>
<UnitPrice>50</UnitPrice>
</Line>
</Check>
PN -
<BankAccountId> : This account should be a 'checking' type.
<ItemId> : Item should have a 'ExpenseAccountRef' tag.
You can test this usecase, using ApiExplorer tool.
Link - https://developer.intuit.com/apiexplorer?apiname=V2QBO
If possible I'll try this using .net devkit on monday and confirm if it is a bug in .net devkit.
Thanks
Adding pseudo code for c# for BillpaymentHeader.
Similarly you can use it for CheckLine:
billheader.ItemsElementName = new ItemsChoiceType[1];
billheader.ItemsElementName[0] = ItemsChoiceType.BankAccountId;
billheader.Items = new object[1];
billheader.Items[0] = new Intuit.Ipp.Data.Qbo.IdType() { idDomain = Intuit.Ipp.Data.Qbo.idDomainEnum.QBO, Value = "1" };
Refer- How to add AccountID or ItemID when creating Checks in QuickBooks
If you have bill already then you can simply use billpayment API to create checks.
URL : https://quickbooks.api.intuit.com/v3/company/111111111111/billpayment?minorversion=4
request JSON data:
{
"VendorRef": {
"value": "1",
"name": "vendor_name"
},
"PayType": "Check",
"CheckPayment": {
"BankAccountRef": {
"value": "1",
"name": "Test Account"
}
},
"TotalAmt": 100.00,
"PrivateNote": "Acct. 1JK90",
"Line": [
{
"Amount": 100.00,
"LinkedTxn": [
{
"TxnId": "1",
"TxnType": "Bill"
}
]
}
]
}

Resources