import hashlib
import hmac
import json
import os
import secrets
import time
import urllib.request
def vantage_request(method, path, payload=None, idempotency_key=None):
key = os.environ["VANTAGE_API_KEY"]
origin = os.environ["VANTAGE_API_ORIGIN"].rstrip("/")
body = b"" if payload is None else json.dumps(
payload, separators=(",", ":")
).encode()
timestamp = str(int(time.time()))
nonce = secrets.token_urlsafe(24)
body_hash = hashlib.sha256(body).hexdigest()
canonical = "\n".join([
method.upper(), path, timestamp, nonce, body_hash
]).encode()
signature = hmac.new(key.encode(), canonical, hashlib.sha256).hexdigest()
headers = {
"X-API-Key": key,
"X-Timestamp": timestamp,
"X-Nonce": nonce,
"X-Signature": signature,
}
if payload is not None:
headers["Content-Type"] = "application/json"
if idempotency_key:
headers["Idempotency-Key"] = idempotency_key
request = urllib.request.Request(
origin + path,
data=body if payload is not None else None,
method=method.upper(),
headers=headers,
)
with urllib.request.urlopen(request, timeout=30) as response:
return json.load(response)