@tari-project/tarijs 0.1.21 → 0.1.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/dist/builders/helpers/index.d.ts +2 -0
  2. package/dist/builders/helpers/index.js +2 -0
  3. package/dist/builders/helpers/submitTransaction.d.ts +13 -0
  4. package/dist/builders/helpers/submitTransaction.js +59 -0
  5. package/dist/builders/helpers/workspace.d.ts +23 -0
  6. package/dist/builders/helpers/workspace.js +29 -0
  7. package/dist/builders/index.d.ts +3 -0
  8. package/dist/builders/index.js +3 -0
  9. package/dist/builders/transaction/TransactionBuilder.d.ts +44 -0
  10. package/dist/builders/transaction/TransactionBuilder.js +164 -0
  11. package/dist/builders/transaction/TransactionRequest.d.ts +27 -0
  12. package/dist/builders/transaction/TransactionRequest.js +67 -0
  13. package/dist/builders/transaction/index.d.ts +2 -0
  14. package/dist/builders/transaction/index.js +2 -0
  15. package/dist/builders/types/Amount.d.ts +23 -0
  16. package/dist/builders/types/Amount.js +93 -0
  17. package/dist/builders/types/Arg.d.ts +1 -0
  18. package/dist/builders/types/Arg.js +1 -0
  19. package/dist/builders/types/Builder.d.ts +47 -0
  20. package/dist/builders/types/Builder.js +1 -0
  21. package/dist/builders/types/ComponentAddress.d.ts +1 -0
  22. package/dist/builders/types/ComponentAddress.js +1 -0
  23. package/dist/builders/types/ConfidentialClaim.d.ts +8 -0
  24. package/dist/builders/types/ConfidentialClaim.js +1 -0
  25. package/dist/builders/types/ConfidentialOutput.d.ts +8 -0
  26. package/dist/builders/types/ConfidentialOutput.js +1 -0
  27. package/dist/builders/types/ConfidentialOutputStatement.d.ts +9 -0
  28. package/dist/builders/types/ConfidentialOutputStatement.js +1 -0
  29. package/dist/builders/types/ConfidentialStatement.d.ts +8 -0
  30. package/dist/builders/types/ConfidentialStatement.js +1 -0
  31. package/dist/builders/types/ConfidentialWithdrawProof.d.ts +7 -0
  32. package/dist/builders/types/ConfidentialWithdrawProof.js +1 -0
  33. package/dist/builders/types/ElgamalVerifiableBalance.d.ts +4 -0
  34. package/dist/builders/types/ElgamalVerifiableBalance.js +1 -0
  35. package/dist/builders/types/Epoch.d.ts +1 -0
  36. package/dist/builders/types/Epoch.js +1 -0
  37. package/dist/builders/types/FinalizeResult.d.ts +20 -0
  38. package/dist/builders/types/FinalizeResult.js +1 -0
  39. package/dist/builders/types/Instruction.d.ts +56 -0
  40. package/dist/builders/types/Instruction.js +1 -0
  41. package/dist/builders/types/ResourceAddress.d.ts +1 -0
  42. package/dist/builders/types/ResourceAddress.js +2 -0
  43. package/dist/builders/types/SubstateDiff.d.ts +7 -0
  44. package/dist/builders/types/SubstateDiff.js +1 -0
  45. package/dist/builders/types/SubstateRequirement.d.ts +5 -0
  46. package/dist/builders/types/SubstateRequirement.js +1 -0
  47. package/dist/builders/types/TemplateAddress.d.ts +1 -0
  48. package/dist/builders/types/TemplateAddress.js +2 -0
  49. package/dist/builders/types/Transaction.d.ts +15 -0
  50. package/dist/builders/types/Transaction.js +1 -0
  51. package/dist/builders/types/TransactionId.d.ts +1 -0
  52. package/dist/builders/types/TransactionId.js +1 -0
  53. package/dist/builders/types/TransactionResult.d.ts +22 -0
  54. package/dist/builders/types/TransactionResult.js +10 -0
  55. package/dist/builders/types/TransactionSignature.d.ts +4 -0
  56. package/dist/builders/types/TransactionSignature.js +1 -0
  57. package/dist/builders/types/UnsignedTransaction.d.ts +12 -0
  58. package/dist/builders/types/UnsignedTransaction.js +1 -0
  59. package/dist/builders/types/VersionedSubstateId.d.ts +5 -0
  60. package/dist/builders/types/VersionedSubstateId.js +1 -0
  61. package/dist/builders/types/ViewableBalanceProof.d.ts +10 -0
  62. package/dist/builders/types/ViewableBalanceProof.js +2 -0
  63. package/dist/builders/types/Workspace.d.ts +3 -0
  64. package/dist/builders/types/Workspace.js +1 -0
  65. package/dist/builders/types/index.d.ts +24 -0
  66. package/dist/builders/types/index.js +2 -0
  67. package/dist/index.d.ts +13 -0
  68. package/dist/index.js +12 -0
  69. package/dist/providers/index.d.ts +16 -0
  70. package/dist/providers/index.js +1 -0
  71. package/dist/providers/metamask/index.d.ts +30 -0
  72. package/dist/providers/metamask/index.js +169 -0
  73. package/dist/providers/metamask/utils.d.ts +38 -0
  74. package/dist/providers/metamask/utils.js +55 -0
  75. package/dist/providers/tari_universe/index.d.ts +3 -0
  76. package/dist/providers/tari_universe/index.js +3 -0
  77. package/dist/providers/tari_universe/provider.d.ts +23 -0
  78. package/dist/providers/tari_universe/provider.js +88 -0
  79. package/dist/providers/tari_universe/types.d.ts +30 -0
  80. package/dist/providers/tari_universe/types.js +1 -0
  81. package/dist/providers/types.d.ts +66 -0
  82. package/dist/providers/types.js +10 -0
  83. package/dist/providers/wallet_daemon/index.d.ts +3 -0
  84. package/dist/providers/wallet_daemon/index.js +3 -0
  85. package/dist/providers/wallet_daemon/provider.d.ts +35 -0
  86. package/dist/providers/wallet_daemon/provider.js +173 -0
  87. package/dist/providers/wallet_daemon/tari_permissions.d.ts +216 -0
  88. package/dist/providers/wallet_daemon/tari_permissions.js +282 -0
  89. package/dist/providers/wallet_daemon/webrtc.d.ts +20 -0
  90. package/dist/providers/wallet_daemon/webrtc.js +201 -0
  91. package/dist/providers/wallet_daemon/webrtc_transport.d.ts +10 -0
  92. package/dist/providers/wallet_daemon/webrtc_transport.js +18 -0
  93. package/dist/providers/walletconnect/index.d.ts +23 -0
  94. package/dist/providers/walletconnect/index.js +217 -0
  95. package/dist/templates/Account.d.ts +65 -0
  96. package/dist/templates/Account.js +31 -0
  97. package/dist/templates/Pool.d.ts +30 -0
  98. package/dist/templates/Pool.js +20 -0
  99. package/dist/templates/Tariswap.d.ts +65 -0
  100. package/dist/templates/Tariswap.js +36 -0
  101. package/dist/templates/TemplateFactory.d.ts +9 -0
  102. package/dist/templates/TemplateFactory.js +18 -0
  103. package/dist/templates/TestFaucet.d.ts +49 -0
  104. package/dist/templates/TestFaucet.js +31 -0
  105. package/dist/templates/index.d.ts +4 -0
  106. package/dist/templates/index.js +4 -0
  107. package/dist/utils.d.ts +2 -0
  108. package/dist/utils.js +22 -0
  109. package/package.json +9 -5
@@ -0,0 +1,201 @@
1
+ class SignaligServer {
2
+ _token;
3
+ _server_url;
4
+ constructor(server_url) {
5
+ console.log(server_url);
6
+ if (server_url !== undefined) {
7
+ this._server_url = server_url;
8
+ }
9
+ else {
10
+ this._server_url = "http://localhost:9100";
11
+ }
12
+ }
13
+ async initToken(permissions) {
14
+ this._token = await this.authLogin(permissions);
15
+ }
16
+ get token() {
17
+ return this._token;
18
+ }
19
+ async jsonRpc(method, token, params) {
20
+ console.log('jsonRpc', method, token, params);
21
+ let id = 0;
22
+ id += 1;
23
+ let address = this._server_url;
24
+ let headers = { 'Content-Type': 'application/json' };
25
+ if (token) {
26
+ headers["Authorization"] = `Bearer ${token}`;
27
+ }
28
+ let response = await fetch(address, {
29
+ method: 'POST',
30
+ body: JSON.stringify({
31
+ method: method,
32
+ jsonrpc: '2.0',
33
+ id: id,
34
+ params: params || {},
35
+ }),
36
+ headers: headers
37
+ });
38
+ let json = await response.json();
39
+ if (json.error) {
40
+ throw json.error;
41
+ }
42
+ return json.result;
43
+ }
44
+ async authLogin(permissions) {
45
+ return await this.jsonRpc("auth.login", undefined, permissions);
46
+ }
47
+ async storeIceCandidate(ice_candidate) {
48
+ return await this.jsonRpc("add.offer_ice_candidate", this._token, ice_candidate);
49
+ }
50
+ async storeOffer(offer) {
51
+ return await this.jsonRpc("add.offer", this._token, offer.sdp);
52
+ }
53
+ async getAnswer() {
54
+ return await this.jsonRpc("get.answer", this._token);
55
+ }
56
+ async getIceCandidates() {
57
+ return await this.jsonRpc("get.answer_ice_candidates", this._token);
58
+ }
59
+ }
60
+ export class TariConnection {
61
+ _peerConnection;
62
+ _dataChannel;
63
+ _signalingServer;
64
+ _callbacks;
65
+ _offer;
66
+ _walletToken;
67
+ // This is public so that user can directly set the onopen callback that will be called once the data channel is open.
68
+ onopen;
69
+ onConnection;
70
+ constructor(signalig_server_url, config) {
71
+ this._peerConnection = new RTCPeerConnection(config || this.config());
72
+ this._dataChannel = this._peerConnection.createDataChannel("tari-data");
73
+ this._signalingServer = new SignaligServer(signalig_server_url);
74
+ this._callbacks = {};
75
+ }
76
+ get token() {
77
+ if (this._walletToken) {
78
+ return this._walletToken;
79
+ }
80
+ return this._signalingServer.token;
81
+ }
82
+ async init(permissions, onConnection) {
83
+ this.onConnection = onConnection;
84
+ await this._signalingServer.initToken(permissions);
85
+ // Setup our receiving end
86
+ this._dataChannel.onmessage = (message) => {
87
+ let response = JSON.parse(message.data);
88
+ console.log('response', response);
89
+ if (!this._callbacks[response.id]) {
90
+ console.error("No callback found for id", response.id);
91
+ return;
92
+ }
93
+ // The response should contain id, to identify the Promise.resolve, that is waiting for this result
94
+ let [resolve, reject] = this._callbacks[response.id];
95
+ delete this._callbacks[response.id];
96
+ if (response.payload?.error) {
97
+ reject(new Error(response.payload.error));
98
+ }
99
+ else {
100
+ resolve(response.payload);
101
+ }
102
+ };
103
+ this._dataChannel.onopen = () => {
104
+ // This should be removed before the release, but it's good for debugging.
105
+ console.log("Data channel is open!");
106
+ this.sendMessage({ id: 0, jsonrpc: "2.0", method: "get.token", params: {} }, this._signalingServer.token)
107
+ .then((walletToken) => {
108
+ if (typeof walletToken !== 'string') {
109
+ throw Error('Received invalid JWT from wallet daemon');
110
+ }
111
+ console.log("Wallet JWT received: ", walletToken);
112
+ this._walletToken = walletToken;
113
+ if (this.onConnection) {
114
+ this.onConnection(this);
115
+ }
116
+ });
117
+ };
118
+ this._peerConnection.onicecandidate = (event) => {
119
+ console.log('event', event);
120
+ if (event?.candidate) {
121
+ console.log("ICE ", event.candidate);
122
+ console.log("ICE ", typeof event.candidate);
123
+ // Store the ice candidates, so the other end can add them
124
+ this._signalingServer.storeIceCandidate(event.candidate).then((resp) => {
125
+ // This should be removed before the release, but it's good for debugging.
126
+ console.log("Candidate stored", resp);
127
+ });
128
+ }
129
+ };
130
+ // Create offer
131
+ this._offer = await this._peerConnection.createOffer();
132
+ // Set the offer as our local sdp, at this point it will start getting the ice candidates
133
+ this._peerConnection.setLocalDescription(this._offer);
134
+ // Store the offer so the other end can set it as a remote sdp
135
+ this._signalingServer.storeOffer(this._offer).then((resp) => {
136
+ // This should be removed before the release, but it's good for debugging.
137
+ console.log("Offer stored", resp);
138
+ });
139
+ await this.signalingServerPolling();
140
+ }
141
+ async setAnswer() {
142
+ // This is called once the other end got the offer and ices and created and store an answer and its ice candidates
143
+ // We get its answer sdp
144
+ let sdp = await this._signalingServer.getAnswer();
145
+ // And its ice candidates
146
+ let iceCandidates = await this._signalingServer.getIceCandidates();
147
+ // For us the answer is remote sdp
148
+ let answer = new RTCSessionDescription({ sdp, type: "answer" });
149
+ this._peerConnection.setRemoteDescription(answer);
150
+ // We add all the ice candidates to connect, the other end is doing the same with our ice candidates
151
+ for (const iceCandidate of iceCandidates) {
152
+ this._peerConnection.addIceCandidate(iceCandidate);
153
+ }
154
+ }
155
+ async signalingServerPolling() {
156
+ // no need to keep retrying if we are already connected to the wallet
157
+ if (this._peerConnection.connectionState === "connected") {
158
+ return;
159
+ }
160
+ try {
161
+ await this.setAnswer();
162
+ }
163
+ catch (error) {
164
+ // we don't need to do anything on error, as the execution will be retried later
165
+ console.error(error);
166
+ }
167
+ // try again later
168
+ setTimeout(async () => {
169
+ await this.signalingServerPolling();
170
+ }, 2000);
171
+ }
172
+ isConnected() {
173
+ return this._dataChannel.readyState === "open";
174
+ }
175
+ // If the last parameter has timeout property e.g. {timeout:1000}, it set the timeout for this call.
176
+ async sendMessage(request, token, timeout_secs = null) {
177
+ if (!this.isConnected) {
178
+ throw new Error("WALLET_DAEMON_NOT_CONNECTED");
179
+ }
180
+ // This should be removed before the release, but it's good for debugging.
181
+ console.log(request, 'timeout', timeout_secs);
182
+ return new Promise((resolve, reject) => {
183
+ // We store the resolve callback for this request,
184
+ // so once the data channel receives a response we know where to return the data
185
+ this._callbacks[request.id] = [resolve, reject];
186
+ if (timeout_secs) {
187
+ // If the user set a timeout which set it here so the promise will be rejected if not fulfilled in time.
188
+ setTimeout(() => {
189
+ delete this._callbacks[request.id];
190
+ reject(new Error("Timeout"));
191
+ }, timeout_secs * 1000);
192
+ }
193
+ // Make the actual call to the wallet daemon
194
+ this._dataChannel.send(JSON.stringify({ token, ...request }));
195
+ });
196
+ }
197
+ // This is our default config, use can set their own stun/turn server in the constructor.
198
+ config() {
199
+ return { iceServers: [{ urls: "stun:stun.l.google.com:19302" }] };
200
+ }
201
+ }
@@ -0,0 +1,10 @@
1
+ import { transports } from "@tari-project/wallet_jrpc_client";
2
+ import { TariConnection } from "./webrtc";
3
+ export declare class WebRtcRpcTransport implements transports.RpcTransport {
4
+ connection: TariConnection;
5
+ constructor(connection: TariConnection);
6
+ static new(connection: TariConnection): WebRtcRpcTransport;
7
+ token(): string | undefined;
8
+ isConnected(): boolean;
9
+ sendRequest<T>(data: transports.RpcRequest, options: transports.RpcTransportOptions): Promise<T>;
10
+ }
@@ -0,0 +1,18 @@
1
+ export class WebRtcRpcTransport {
2
+ connection;
3
+ constructor(connection) {
4
+ this.connection = connection;
5
+ }
6
+ static new(connection) {
7
+ return new WebRtcRpcTransport(connection);
8
+ }
9
+ token() {
10
+ return this.connection.token;
11
+ }
12
+ isConnected() {
13
+ return this.connection.isConnected();
14
+ }
15
+ sendRequest(data, options) {
16
+ return this.connection.sendMessage(data, options.token);
17
+ }
18
+ }
@@ -0,0 +1,23 @@
1
+ import { TariProvider } from "../index";
2
+ import { SubmitTransactionRequest, TransactionResult, SubmitTransactionResponse, VaultBalances, TemplateDefinition, Substate, Account, ListSubstatesResponse } from "../types";
3
+ import UniversalProvider from '@walletconnect/universal-provider';
4
+ import { SubstateType } from "@tari-project/wallet_jrpc_client";
5
+ export declare class WalletConnectTariProvider implements TariProvider {
6
+ providerName: string;
7
+ projectId: string;
8
+ wcProvider: UniversalProvider | null;
9
+ wcSession: any | null;
10
+ constructor(projectId: string);
11
+ connect(): Promise<void>;
12
+ private sendRequest;
13
+ isConnected(): boolean;
14
+ getAccount(): Promise<Account>;
15
+ getSubstate(substate_address: string): Promise<Substate>;
16
+ listSubstates(filter_by_template: string | null, filter_by_type: SubstateType | null, limit: number | null, offset: number | null): Promise<ListSubstatesResponse>;
17
+ createFreeTestCoins(): Promise<Account>;
18
+ submitTransaction(req: SubmitTransactionRequest): Promise<SubmitTransactionResponse>;
19
+ getTransactionResult(transactionId: string): Promise<TransactionResult>;
20
+ getTemplateDefinition(template_address: string): Promise<TemplateDefinition>;
21
+ getPublicKey(branch: string, index: number): Promise<string>;
22
+ getConfidentialVaultBalances(viewKeyId: number, vaultId: string, min: number | null, max: number | null): Promise<VaultBalances>;
23
+ }
@@ -0,0 +1,217 @@
1
+ import { TransactionStatus, } from "../types";
2
+ import UniversalProvider from '@walletconnect/universal-provider';
3
+ import { WalletConnectModal } from '@walletconnect/modal';
4
+ import { stringToSubstateId, substateIdToString } from "@tari-project/wallet_jrpc_client";
5
+ const walletConnectParams = {
6
+ requiredNamespaces: {
7
+ tari: {
8
+ methods: [
9
+ 'tari_getSubstate',
10
+ 'tari_getDefaultAccount',
11
+ 'tari_getAccountBalances',
12
+ 'tari_submitTransaction',
13
+ 'tari_getTransactionResult',
14
+ 'tari_getTemplate',
15
+ 'tari_createKey',
16
+ 'tari_viewConfidentialVaultBalance',
17
+ 'tari_createFreeTestCoins',
18
+ 'tari_listSubstates'
19
+ ],
20
+ chains: [
21
+ 'tari:devnet',
22
+ ],
23
+ events: ['chainChanged", "accountsChanged']
24
+ }
25
+ }
26
+ };
27
+ export class WalletConnectTariProvider {
28
+ providerName = "WalletConnect";
29
+ projectId;
30
+ wcProvider;
31
+ wcSession;
32
+ constructor(projectId) {
33
+ this.projectId = projectId;
34
+ this.wcProvider = null;
35
+ this.wcSession = null;
36
+ }
37
+ async connect() {
38
+ if (this.wcProvider && this.wcSession)
39
+ return;
40
+ // initialize WalletConnect
41
+ const projectId = this.projectId;
42
+ this.wcProvider = await UniversalProvider.init({
43
+ projectId,
44
+ // TODO: parameterize the relay URL
45
+ relayUrl: 'wss://relay.walletconnect.com'
46
+ });
47
+ // open UI modal with the connection URI
48
+ const { uri, approval } = await this.wcProvider.client.connect(walletConnectParams);
49
+ const walletConnectModal = new WalletConnectModal({
50
+ projectId
51
+ });
52
+ if (uri) {
53
+ walletConnectModal.openModal({ uri });
54
+ }
55
+ // wait for the wallet to approve the connection
56
+ console.log("waiting for session approval from the wallet app");
57
+ const session = await approval();
58
+ // at this point session is open
59
+ console.log("session approved by the wallet");
60
+ this.wcSession = session;
61
+ }
62
+ async sendRequest(method, params) {
63
+ if (!this.wcProvider) {
64
+ throw "WalletConnect provider not initialized";
65
+ }
66
+ if (!this.wcSession) {
67
+ throw "WalletConnect session not initialized";
68
+ }
69
+ const requestResult = await this.wcProvider.client.request({
70
+ topic: this.wcSession.topic,
71
+ chainId: 'tari:devnet',
72
+ request: {
73
+ method,
74
+ params
75
+ }
76
+ });
77
+ console.log({ requestResult });
78
+ return requestResult;
79
+ }
80
+ isConnected() {
81
+ // TODO: check status in the session
82
+ return this.wcSession !== null;
83
+ }
84
+ async getAccount() {
85
+ const { account, public_key } = await this.sendRequest('tari_getDefaultAccount', {});
86
+ const { balances } = await this.sendRequest('tari_getAccountBalances', { account: { ComponentAddress: account.address.Component }, refresh: false
87
+ });
88
+ return {
89
+ account_id: account.key_index,
90
+ address: account.address.Component,
91
+ public_key,
92
+ // TODO: should be vaults not resources
93
+ resources: balances.map((b) => ({
94
+ type: b.resource_type,
95
+ resource_address: b.resource_address,
96
+ balance: b.balance + b.confidential_balance,
97
+ vault_id: ('Vault' in b.vault_address) ? b.vault_address.Vault : b.vault_address,
98
+ token_symbol: b.token_symbol,
99
+ }))
100
+ };
101
+ }
102
+ async getSubstate(substate_address) {
103
+ const substateId = stringToSubstateId(substate_address);
104
+ const method = 'tari_getSubstate';
105
+ const params = { substate_id: substateId };
106
+ const { value, record } = await this.sendRequest(method, params);
107
+ return {
108
+ value,
109
+ address: {
110
+ substate_id: substateIdToString(record.substate_id),
111
+ version: record.version
112
+ }
113
+ };
114
+ }
115
+ async listSubstates(filter_by_template, filter_by_type, limit, offset) {
116
+ const method = 'tari_listSubstates';
117
+ const params = {
118
+ filter_by_template,
119
+ filter_by_type,
120
+ limit,
121
+ offset
122
+ };
123
+ const res = await this.sendRequest(method, params);
124
+ const substates = res.substates.map((s) => ({
125
+ substate_id: substateIdToString(s.substate_id),
126
+ module_name: s.module_name,
127
+ version: s.version,
128
+ template_address: s.template_address
129
+ }));
130
+ return { substates };
131
+ }
132
+ async createFreeTestCoins() {
133
+ const method = 'tari_createFreeTestCoins';
134
+ const params = {
135
+ account: { Name: "template_web" },
136
+ amount: 1000000,
137
+ max_fee: null,
138
+ key_id: 0
139
+ };
140
+ const res = await this.sendRequest(method, params);
141
+ return {
142
+ account_id: res.account.key_index,
143
+ address: res.account.address.Component,
144
+ public_key: res.public_key,
145
+ resources: []
146
+ };
147
+ }
148
+ async submitTransaction(req) {
149
+ const method = 'tari_submitTransaction';
150
+ const params = {
151
+ transaction: null,
152
+ signing_key_index: req.account_id,
153
+ fee_instructions: req.fee_instructions,
154
+ instructions: req.instructions,
155
+ inputs: req.required_substates.map((s) => ({
156
+ // TODO: Hmm The bindings want a SubstateId object, but the wallet only wants a string. Any is used to skip type checking here
157
+ substate_id: s.substate_id,
158
+ version: s.version
159
+ })),
160
+ input_refs: [],
161
+ override_inputs: false,
162
+ is_dry_run: req.is_dry_run,
163
+ proof_ids: [],
164
+ min_epoch: null,
165
+ max_epoch: null,
166
+ };
167
+ const res = await this.sendRequest(method, params);
168
+ return { transaction_id: res.transaction_id };
169
+ }
170
+ async getTransactionResult(transactionId) {
171
+ const res = await this.sendRequest('tari_getTransactionResult', { transaction_id: transactionId });
172
+ return {
173
+ transaction_id: transactionId,
174
+ status: convertStringToTransactionStatus(res.status),
175
+ result: res.result,
176
+ };
177
+ }
178
+ async getTemplateDefinition(template_address) {
179
+ let resp = await this.sendRequest('tari_getTemplate', { template_address });
180
+ return resp.template_definition;
181
+ }
182
+ async getPublicKey(branch, index) {
183
+ const res = await this.sendRequest('tari_createKey', { branch: branch, specific_index: index });
184
+ return res.public_key;
185
+ }
186
+ async getConfidentialVaultBalances(viewKeyId, vaultId, min, max) {
187
+ const method = 'tari_viewConfidentialVaultBalance';
188
+ const params = {
189
+ view_key_id: viewKeyId,
190
+ vault_id: vaultId,
191
+ minimum_expected_value: min,
192
+ maximum_expected_value: max,
193
+ };
194
+ const res = await this.sendRequest(method, params);
195
+ return { balances: res.balances };
196
+ }
197
+ }
198
+ function convertStringToTransactionStatus(status) {
199
+ switch (status) {
200
+ case "New":
201
+ return TransactionStatus.New;
202
+ case "DryRun":
203
+ return TransactionStatus.DryRun;
204
+ case "Pending":
205
+ return TransactionStatus.Pending;
206
+ case "Accepted":
207
+ return TransactionStatus.Accepted;
208
+ case "Rejected":
209
+ return TransactionStatus.Rejected;
210
+ case "InvalidTransaction":
211
+ return TransactionStatus.InvalidTransaction;
212
+ case "OnlyFeeAccepted":
213
+ return TransactionStatus.OnlyFeeAccepted;
214
+ default:
215
+ throw new Error(`Unknown status: ${status}`);
216
+ }
217
+ }
@@ -0,0 +1,65 @@
1
+ import { ConfidentialWithdrawProof, NonFungibleId, ResourceAddress } from "@tari-project/typescript-bindings";
2
+ import { Amount } from "../builders/types/Amount";
3
+ import { TariMethodDefinition, WorkspaceArg } from "../builders/types";
4
+ import { TemplateFactory } from "./TemplateFactory";
5
+ /**
6
+ * Adds a fee instruction that calls the "take_fee" method on a component.
7
+ * This method must exist and return a Bucket with containing revealed confidential XTR resource.
8
+ * This allows the fee to originate from sources other than the transaction sender's account.
9
+ * The fee instruction will lock up the "max_fee" amount for the duration of the transaction.
10
+ * @param componentAddress
11
+ * @param maxFee
12
+ * @returns
13
+ */
14
+ interface PayFeeMethod extends TariMethodDefinition {
15
+ methodName: "pay_fee";
16
+ args?: [Amount];
17
+ }
18
+ interface PayFeeConfidentialMethod extends TariMethodDefinition {
19
+ methodName: "pay_fee_confidential";
20
+ args?: [ConfidentialWithdrawProof];
21
+ }
22
+ interface WithdrawMethod extends TariMethodDefinition {
23
+ methodName: "withdraw";
24
+ args?: [string, Amount];
25
+ }
26
+ interface DepositMethod extends TariMethodDefinition {
27
+ methodName: "deposit";
28
+ args?: WorkspaceArg[];
29
+ }
30
+ interface CreateProofForResourceMethod extends TariMethodDefinition {
31
+ methodName: "create_proof_for_resource";
32
+ args?: [ResourceAddress];
33
+ }
34
+ interface CreateProofByAmountMethod extends TariMethodDefinition {
35
+ methodName: "create_proof_by_amount";
36
+ args?: [ResourceAddress, Amount];
37
+ }
38
+ interface CreateProofByNonFungibleIdsMethod extends TariMethodDefinition {
39
+ methodName: "create_proof_by_non_fungible_ids";
40
+ args?: [ResourceAddress, NonFungibleId[]];
41
+ }
42
+ interface BalanceMethod extends TariMethodDefinition {
43
+ methodName: "balance";
44
+ args?: [ResourceAddress];
45
+ }
46
+ interface GetBalancesMethod extends TariMethodDefinition {
47
+ methodName: "get_balances";
48
+ args?: [];
49
+ }
50
+ export declare class AccountTemplate extends TemplateFactory {
51
+ templateAddress: string;
52
+ deposit: DepositMethod;
53
+ withdraw: WithdrawMethod;
54
+ createProofByAmount: CreateProofByAmountMethod;
55
+ createProofByNonFungibleIds: CreateProofByNonFungibleIdsMethod;
56
+ createProofForResource: CreateProofForResourceMethod;
57
+ balance: BalanceMethod;
58
+ getBalances: GetBalancesMethod;
59
+ payFee: PayFeeMethod;
60
+ payFeeConfidential: PayFeeConfidentialMethod;
61
+ constructor(templateAddress: string);
62
+ protected _initFunctions(): void;
63
+ protected _initMethods(): void;
64
+ }
65
+ export {};
@@ -0,0 +1,31 @@
1
+ import { TemplateFactory } from "./TemplateFactory";
2
+ export class AccountTemplate extends TemplateFactory {
3
+ templateAddress;
4
+ deposit;
5
+ withdraw;
6
+ createProofByAmount;
7
+ createProofByNonFungibleIds;
8
+ createProofForResource;
9
+ balance;
10
+ getBalances;
11
+ payFee;
12
+ payFeeConfidential;
13
+ constructor(templateAddress) {
14
+ super(templateAddress);
15
+ this.templateAddress = templateAddress;
16
+ this._initFunctions();
17
+ this._initMethods();
18
+ }
19
+ _initFunctions() { }
20
+ _initMethods() {
21
+ this.deposit = this._defineMethod("deposit");
22
+ this.withdraw = this._defineMethod("withdraw");
23
+ this.createProofByAmount = this._defineMethod("create_proof_by_amount");
24
+ this.createProofByNonFungibleIds = this._defineMethod("create_proof_by_non_fungible_ids");
25
+ this.createProofForResource = this._defineMethod("create_proof_for_resource");
26
+ this.balance = this._defineMethod("balance");
27
+ this.getBalances = this._defineMethod("get_balances");
28
+ this.payFee = this._defineMethod("pay_fee");
29
+ this.payFeeConfidential = this._defineMethod("pay_fee_confidential");
30
+ }
31
+ }
@@ -0,0 +1,30 @@
1
+ import { TariMethodDefinition } from "../builders/types/Builder";
2
+ import { WorkspaceArg } from "../builders/types/Workspace";
3
+ import { TemplateFactory } from "./TemplateFactory";
4
+ interface CreatePool extends TariMethodDefinition {
5
+ methodName: "create_pool";
6
+ args?: [string, string];
7
+ }
8
+ interface AddLiquidityMethod extends TariMethodDefinition {
9
+ methodName: "add_liquidity";
10
+ args?: WorkspaceArg[];
11
+ }
12
+ interface RemoveLiquidityMethod extends TariMethodDefinition {
13
+ methodName: "remove_liquidity";
14
+ args?: WorkspaceArg[];
15
+ }
16
+ interface SwapMethod extends TariMethodDefinition {
17
+ methodName: "swap";
18
+ args?: (WorkspaceArg | string)[];
19
+ }
20
+ export declare class PoolTemplate extends TemplateFactory {
21
+ templateAddress: string;
22
+ createPool: CreatePool;
23
+ addLiquidity: AddLiquidityMethod;
24
+ removeLiquidity: RemoveLiquidityMethod;
25
+ swap: SwapMethod;
26
+ constructor(templateAddress: string);
27
+ protected _initFunctions(): void;
28
+ protected _initMethods(): void;
29
+ }
30
+ export {};
@@ -0,0 +1,20 @@
1
+ import { TemplateFactory } from "./TemplateFactory";
2
+ export class PoolTemplate extends TemplateFactory {
3
+ templateAddress;
4
+ createPool;
5
+ addLiquidity;
6
+ removeLiquidity;
7
+ swap;
8
+ constructor(templateAddress) {
9
+ super(templateAddress);
10
+ this.templateAddress = templateAddress;
11
+ this._initFunctions();
12
+ this._initMethods();
13
+ }
14
+ _initFunctions() { }
15
+ _initMethods() {
16
+ this.addLiquidity = this._defineMethod("add_liquidity");
17
+ this.removeLiquidity = this._defineMethod("remove_liquidity");
18
+ this.swap = this._defineMethod("swap");
19
+ }
20
+ }
@@ -0,0 +1,65 @@
1
+ import { Amount, ConfidentialWithdrawProof, ResourceAddress } from "../builders/types";
2
+ import { TariFunctionDefinition, TariMethodDefinition, WorkspaceArg } from "../builders/types";
3
+ import { TemplateFactory } from "./TemplateFactory";
4
+ interface NewPoolFunction extends TariFunctionDefinition {
5
+ functionName: "new";
6
+ args?: [ResourceAddress, ResourceAddress, Amount];
7
+ }
8
+ interface MintFunction extends TariFunctionDefinition {
9
+ functionName: "mint";
10
+ args?: [Amount];
11
+ }
12
+ interface MintWithSymbolFunction extends TariFunctionDefinition {
13
+ functionName: "mint_with_symbol";
14
+ args?: [Amount, string];
15
+ }
16
+ interface PayFeeMethod extends TariMethodDefinition {
17
+ methodName: "pay_fee";
18
+ args?: [string];
19
+ }
20
+ interface PayFeeConfidentialMethod extends TariMethodDefinition {
21
+ methodName: "pay_fee_confidential";
22
+ args?: [ConfidentialWithdrawProof];
23
+ }
24
+ interface TotalSupplyMethod extends TariMethodDefinition {
25
+ methodName: "total_supply";
26
+ args?: [];
27
+ }
28
+ interface WithdrawMethod extends TariMethodDefinition {
29
+ methodName: "withdraw";
30
+ args?: [string, string];
31
+ }
32
+ interface AddLiquidityMethod extends TariMethodDefinition {
33
+ methodName: "add_liquidity";
34
+ args?: WorkspaceArg[];
35
+ }
36
+ interface RemoveLiquidityMethod extends TariMethodDefinition {
37
+ methodName: "remove_liquidity";
38
+ args?: WorkspaceArg[];
39
+ }
40
+ interface DepositMethod extends TariMethodDefinition {
41
+ methodName: "deposit";
42
+ args?: WorkspaceArg[];
43
+ }
44
+ interface SwapMethod extends TariMethodDefinition {
45
+ methodName: "swap";
46
+ args?: (WorkspaceArg | string)[];
47
+ }
48
+ export declare class TariswapTemplate extends TemplateFactory {
49
+ templateAddress: string;
50
+ newPool: NewPoolFunction;
51
+ mint: MintFunction;
52
+ mintWithSymbol: MintWithSymbolFunction;
53
+ totalSupply: TotalSupplyMethod;
54
+ payFee: PayFeeMethod;
55
+ payFeeConfidential: PayFeeConfidentialMethod;
56
+ withdraw: WithdrawMethod;
57
+ addLiquidity: AddLiquidityMethod;
58
+ removeLiquidity: RemoveLiquidityMethod;
59
+ deposit: DepositMethod;
60
+ swap: SwapMethod;
61
+ constructor(templateAddress: string);
62
+ protected _initFunctions(): void;
63
+ protected _initMethods(): void;
64
+ }
65
+ export {};