/
account.js
80 lines (76 loc) · 2.12 KB
/
account.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import {
createStacksPrivateKey,
getPublicKey,
addressFromPublicKeys,
AddressVersion,
AddressHashMode,
callReadOnlyFunction,
bufferCVFromString,
ClarityType,
cvToString,
} from '@stacks/transactions';
import {
accountsApi,
BNS_CONTRACT_NAME,
GENESIS_CONTRACT_ADDRESS,
NETWORK,
STACKS_API_ACCOUNTS_URL,
} from './constants';
export function getStacksAccount(appPrivateKey) {
const privateKey = createStacksPrivateKey(appPrivateKey);
const publicKey = getPublicKey(privateKey);
const address = addressFromPublicKeys(
AddressVersion.TestnetSingleSig,
AddressHashMode.SerializeP2PKH,
1,
[publicKey]
);
return { privateKey, address };
}
export async function getUserAddress(userSession, username) {
const parts = username.split('.');
if (parts.length === 2) {
console.log(parts);
const result = await callReadOnlyFunction({
contractAddress: GENESIS_CONTRACT_ADDRESS,
contractName: BNS_CONTRACT_NAME,
functionName: 'name-resolve',
functionArgs: [bufferCVFromString(parts[1]), bufferCVFromString(parts[0])],
network: NETWORK,
senderAddress: GENESIS_CONTRACT_ADDRESS,
});
if (result.type === ClarityType.ResponseOk) {
return { address: cvToString(result.value.data.owner) };
} else {
return undefined;
}
} else {
return undefined;
}
}
/**
* Uses the AccountsApi of the stacks blockchain api client library,
* returns the stacks balance object with property `balance` in decimal.
*/
export function fetchAccount(addressAsString) {
console.log(`Checking account "${addressAsString}"`);
if (addressAsString) {
return accountsApi
.getAccountBalance({ principal: addressAsString })
.then(response => response.stx);
} else {
return Promise.reject();
}
}
/**
* Uses the RCP api of the stacks node directly,
* returns the json object with property `balance` in hex.
*/
export function fetchAccount2(addressAsString) {
console.log('Checking account');
const balanceUrl = `${STACKS_API_ACCOUNTS_URL}/${addressAsString}`;
return fetch(balanceUrl).then(r => {
console.log({ r });
return r.json();
});
}