Developers
Search…
Example
Fetch user's on-chain portfolio
The following example connects to the Zerion Websocket API and fetches the portfolio of a given Ethereum address.
JavaScript
Python

1. Copy and paste the example below to quickstart.js

1
let io = require('socket.io-client')
2
3
const BASE_URL = 'wss://api-v4.zerion.io/';
4
5
function verify(request, response) {
6
// each value in request payload must be found in response meta
7
return Object.keys(request.payload).every(key => {
8
const requestValue = request.payload[key];
9
const responseMetaValue = response.meta[key];
10
if (typeof requestValue === 'object') {
11
return JSON.stringify(requestValue) === JSON.stringify(responseMetaValue);
12
}
13
return responseMetaValue === requestValue;
14
});
15
}
16
17
const addressSocket = {
18
namespace: 'address',
19
socket: io(`${BASE_URL}address`, {
20
transports: ['websocket'],
21
timeout: 60000,
22
query: {
23
api_token:
24
'Demo.ukEVQp6L5vfgxcz4sBke7XvS873GMYHy',
25
},
26
}),
27
};
28
29
function get(socketNamespace, requestBody) {
30
return new Promise(resolve => {
31
const { socket, namespace } = socketNamespace;
32
function handleReceive(data) {
33
if (verify(requestBody, data)) {
34
unsubscribe();
35
resolve(data);
36
}
37
}
38
const model = requestBody.scope[0];
39
function unsubscribe() {
40
socket.off(`received ${namespace} ${model}`, handleReceive);
41
socket.emit('unsubscribe', requestBody);
42
}
43
socket.emit('get', requestBody);
44
socket.on(`received ${namespace} ${model}`, handleReceive);
45
});
46
}
47
48
get(addressSocket, {
49
scope: ['portfolio'],
50
payload: {
51
address: '0x7e5ce10826ee167de897d262fcc9976f609ecd2b',
52
currency: 'usd',
53
portfolio_fields: 'all'
54
},
55
}).then(response => {
56
console.log(response.payload.portfolio);
57
});
Copied!

2. Run it using node

1
node quickstart.js
Copied!

1. Copy and paste the example below to quickstart.py

1
import asyncio
2
import socketio
3
4
URI = 'wss://api-v4.zerion.io/'
5
API_TOKEN = 'Demo.ukEVQp6L5vfgxcz4sBke7XvS873GMYHy'
6
ORIGIN = 'http://localhost:3000'
7
8
sio = socketio.AsyncClient(logger=False, engineio_logger=False)
9
10
CONNECTED_TO_SOCKET = False
11
12
ADDRESS_PORTFOLIO = None
13
ADDRESS_ASSETS = None
14
ADDRESS_DEPOSITS = None
15
ADDRESS_LOANS = None
16
ADDRESS_STAKED_ASSETS = None
17
ADDRESS_LOCKED_ASSETS = None
18
19
20
@sio.event(namespace='/address')
21
async def connect():
22
global CONNECTED_TO_SOCKET
23
print('Connected to /address namespace!')
24
CONNECTED_TO_SOCKET = True
25
26
27
async def connect_to_socket():
28
await sio.connect(
29
f'{URI}/?api_token={API_TOKEN}',
30
headers={'Origin': ORIGIN},
31
namespaces=['/address'],
32
transports=['websocket']
33
)
34
35
36
@sio.on('received address portfolio', namespace='/address')
37
def received_address_portfolio(data):
38
global ADDRESS_PORTFOLIO
39
print('Address portfolio is received')
40
ADDRESS_PORTFOLIO = data['payload']['portfolio']
41
42
@sio.on('received address assets', namespace='/address')
43
def received_address_assets(data):
44
global ADDRESS_ASSETS
45
print('Address assets are received')
46
ADDRESS_ASSETS = data['payload']['assets']
47
48
@sio.on('received address deposits', namespace='/address')
49
def received_address_assets(data):
50
global ADDRESS_DEPOSITS
51
print('Address deposits are received')
52
ADDRESS_DEPOSITS = data['payload']['deposits']
53
54
@sio.on('received address loans', namespace='/address')
55
def received_address_assets(data):
56
global ADDRESS_LOANS
57
print('Address loans are received')
58
ADDRESS_LOANS = data['payload']['loans']
59
60
@sio.on('received address staked-assets', namespace='/address')
61
def received_address_assets(data):
62
global ADDRESS_STAKED_ASSETS
63
print('Address staked assets are received')
64
ADDRESS_STAKED_ASSETS = data['payload']['staked-assets']
65
66
@sio.on('received address locked-assets', namespace='/address')
67
def received_address_assets(data):
68
global ADDRESS_LOCKED_ASSETS
69
print('Address locked assets are received')
70
ADDRESS_LOCKED_ASSETS = data['payload']['locked-assets']
71
72
def results_ready() -> bool:
73
requested_entities = (
74
ADDRESS_PORTFOLIO, ADDRESS_ASSETS, ADDRESS_DEPOSITS,
75
ADDRESS_LOANS, ADDRESS_STAKED_ASSETS, ADDRESS_LOCKED_ASSETS
76
)
77
return not any(x is None for x in requested_entities)
78
79
async def main(address: str):
80
# Initiate the connection with the websocket
81
await connect_to_socket()
82
83
# Wait until the connection is established
84
while not CONNECTED_TO_SOCKET:
85
await asyncio.sleep(0)
86
87
# Request address information
88
await sio.emit('subscribe', {
89
'scope': ['portfolio', 'assets', 'deposits', 'loans', 'staked-assets', 'locked-assets'],
90
'payload': {
91
'address': address,
92
'currency': 'usd',
93
'portfolio_fields': 'all'
94
}
95
}, namespace='/address')
96
97
# Wait until all information about the address is received
98
while not results_ready():
99
await asyncio.sleep(0)
100
101
print('------')
102
print(
103
f'Address {address} has:',
104
f' - {len(ADDRESS_ASSETS)} assets worth of ${ADDRESS_PORTFOLIO["assets_value"]}',
105
f' - {len(ADDRESS_DEPOSITS)} deposits worth of ${ADDRESS_PORTFOLIO["deposited_value"]}',
106
f' - {len(ADDRESS_LOANS)} loans worth of ${ADDRESS_PORTFOLIO["borrowed_value"]}',
107
f' - {len(ADDRESS_STAKED_ASSETS)} staked assets worth of ${ADDRESS_PORTFOLIO["staked_value"]}',
108
f' - {len(ADDRESS_LOCKED_ASSETS)} locked assets worth of ${ADDRESS_PORTFOLIO["locked_value"]}',
109
sep='\n',
110
)
111
112
if __name__ == '__main__':
113
test_address = '0x7e5ce10826ee167de897d262fcc9976f609ecd2b'
114
loop = asyncio.get_event_loop()
115
loop.run_until_complete(main(test_address))
116
Copied!

2. Run it using python

1
python3 quickstart.py
Copied!
Last modified 8mo ago
Copy link