This Motoko canister performs an HTTP GET request to the Internet Computer public ledger API to retrieve a list of transactions for a specified account identifier.
The canister demonstrates the use of HTTP outcalls in Motoko using the ic:aaaaa-aa
system interface. Specifically, it issues an HTTP GET request to the ledger , parses the JSON response, and returns it to the caller.
public func get_transaction(account_identifier : Text, l : Nat) : async Json.Json
This function takes the following parameters:
account_identifier
: AText
value representing the principal's ICP account in its string form.l
: ANat
indicating the number of transactions to retrieve. The value must not exceed 100.
If l > 100
, the function returns a JSON string indicating that the limit has been exceeded.
The function constructs an HTTPS GET request to the following endpoint:
https://ledger-api.internetcomputer.org/v2/accounts/{account_identifier}/transactions?limit={l}&sort_by=-block_height
The sort_by=-block_height
parameter ensures that transactions are returned in reverse chronological order.
-
Method:
GET
-
URL: Constructed dynamically using the provided account identifier and limit.
-
Headers:
Host
:ledger-api.internetcomputer.org:443
Accept
:application/json
User-Agent
:motoko-canister
//not required
-
Body:
null
-
Max Response Size:
null
-
Cycles: 600,000,000 cycles allocated per request
The canister attempts to decode the response body as UTF-8 text. If decoding succeeds, it proceeds to parse the text as JSON using the mo:json
library. If parsing fails, the function returns a JSON string indicating the error encountered (e.g., invalid token, unexpected EOF).
If decoding fails entirely, the function returns a JSON string stating "No value returned"
.
All successful responses are returned as Json.Json
values.
- The maximum number of transactions that can be fetched per request is 100.
- The function does not implement retry logic for failed HTTP requests.
- Canister must have sufficient cycles to perform the HTTP outcall.
let result = await get_transaction(
"aabbccddeeff00112233445566778899aabbccddeeff00112233445566778899",
25
);
This call retrieves the 25 most recent transactions associated with the specified ICP account.