-
Notifications
You must be signed in to change notification settings - Fork 22
/
index.ts
203 lines (167 loc) · 7.08 KB
/
index.ts
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
const Buffer = require('buffer/').Buffer
import { Contracts } from '~@vite/vitejs-constant';
import { checkParams, isArray, blake2bHex } from '~@vite/vitejs-utils';
import { isValidAddress, AddressType, getOriginalAddressFromAddress } from '~@vite/vitejs-wallet/address';
import { decodeParameters, encodeFunctionCall, getAbiByType, getAbiByName } from '~@vite/vitejs-abi';
import { Default_Contract_TransactionType, encodeContractList, getTransactionType, decodeContractAccountBlock } from '~@vite/vitejs-accountblock/utils';
import { Address, AccountBlockType, Transaction, Hex, Base64, BigInt } from './type';
import Provider from './provider';
class ViteAPIClass extends Provider {
private customTransactionType: Object;
constructor(provider: any, onInitCallback: Function) {
super(provider, onInitCallback);
// { [funcSign + contractAddress]: { contractAddress, abi, transactionType } }
this.customTransactionType = {};
}
get transactionType() {
return Object.assign({}, this.customTransactionType, Default_Contract_TransactionType);
}
// contractList = { 'transactionTypeName': { contractAddress, abi } }
addTransactionType(contractList: Object = {}) {
for (const transactionType in contractList) {
if (Contracts[transactionType]) {
throw new Error(`Please rename it. Your transactionType ${ transactionType } conflicts with default transactionType.`);
}
if (this.customTransactionType && this.customTransactionType[transactionType]) {
throw new Error(`Please rename it. Your transactionType ${ transactionType } conflicts with custom transactionType.`);
}
}
const transactionTypeAfterEncode = encodeContractList(contractList);
this.customTransactionType = Object.assign({}, this.customTransactionType, transactionTypeAfterEncode);
}
async getBalanceInfo(address: Address): Promise<{ balance: Object; unreceived: Object }> {
const err = checkParams({ address }, ['address'], [{
name: 'address',
func: isValidAddress
}]);
if (err) {
throw err;
}
const data = await this.batch([ {
methodName: 'ledger_getAccountInfoByAddress',
params: [address]
}, {
methodName: 'ledger_getUnreceivedTransactionSummaryByAddress',
params: [address]
} ]);
if (!data || (data instanceof Array && data.length < 2)) {
return {
balance: null,
unreceived: null
};
}
if (data[0].error) {
throw data[0].error;
}
if (data[1].error) {
throw data[1].error;
}
return {
balance: data[0].result,
unreceived: data[1].result
};
}
async getTransactionList({ address, pageIndex, pageSize = 50 }: {
address: Address; pageIndex: number; pageSize?: number;
}, decodeTxTypeList: 'all' | string[] = 'all'): Promise<Transaction[]> {
const err = checkParams({ address, pageIndex, decodeTxTypeList }, [ 'address', 'pageIndex' ], [ {
name: 'address',
func: isValidAddress
}, {
name: 'decodeTxTypeList',
func: function (_d) {
return _d === 'all' || _d === 'none' || isArray(_d);
},
msg: '\'all\' || \'none\' || TransactionType[]'
} ]);
if (err) {
throw err;
}
pageIndex = pageIndex >= 0 ? pageIndex : 0;
const data = await this.request('ledger_getAccountBlocksByAddress', address, pageIndex, pageSize);
const rawList = data || [];
const list: Transaction[] = [];
rawList.forEach((accountBlock: AccountBlockType) => {
const transaction: Transaction = accountBlock;
const { abi, transactionType, contractAddress } = getTransactionType(accountBlock, this.customTransactionType);
transaction.transactionType = transactionType;
const isDecodeTx = contractAddress
&& abi
&& (
decodeTxTypeList === 'all'
|| (decodeTxTypeList.length && decodeTxTypeList.indexOf(transactionType) !== -1
)
);
if (isDecodeTx) {
transaction.contractParams = contractAddress && abi
? decodeContractAccountBlock({ accountBlock, contractAddress, abi })
: null;
}
list.push(transaction);
});
return list;
}
async callOffChainContract({ address, abi, code, params }) {
const err = checkParams({ address, abi }, [ 'address', 'abi' ], [{
name: 'address',
func: _a => isValidAddress(_a) === AddressType.Contract
}]);
if (err) {
throw err;
}
const offchainAbi = getAbiByType(abi, 'offchain');
if (!offchainAbi) {
throw new Error('Can\'t find abi that type is offchain');
}
const data = encodeFunctionCall(offchainAbi, params || []);
const result = await this.request('contract_callOffChainMethod', {
address,
code,
data: Buffer.from(data, 'hex').toString('base64')
});
if (!result) {
return null;
}
const hexResult = Buffer.from(result, 'base64').toString('hex');
return decodeParameters(offchainAbi.outputs, hexResult);
}
async queryContractState({ address, abi, methodName, params }) {
const err = checkParams({ address, abi }, [ 'address', 'abi' ], [{
name: 'address',
func: _a => isValidAddress(_a) === AddressType.Contract
}]);
if (err) {
throw err;
}
const methodAbi = getAbiByName(abi, methodName);
if (!methodAbi) {
throw new Error('Can\'t find abi for the method');
}
const data = encodeFunctionCall(methodAbi, params || []);
const result = await this.request('contract_query', {
address,
data: Buffer.from(data, 'hex').toString('base64')
});
if (!result) {
return null;
}
const hexResult = Buffer.from(result, 'base64').toString('hex');
return decodeParameters(methodAbi.outputs, hexResult);
}
async getNonce({ difficulty, previousHash, address }: {
difficulty: BigInt;
previousHash: Hex;
address: Address;
}): Promise<Base64> {
const err = checkParams({ difficulty, previousHash, address }, [ 'address', 'difficulty', 'previousHash' ]);
if (err) {
throw err;
}
const originalAddress = getOriginalAddressFromAddress(address);
const getNonceHashBuffer = Buffer.from(originalAddress + previousHash, 'hex');
const getNonceHash = blake2bHex(getNonceHashBuffer, null, 32);
return this.request('util_getPoWNonce', difficulty, getNonceHash);
}
}
export const ViteAPI = ViteAPIClass;
export default ViteAPI;