-
Notifications
You must be signed in to change notification settings - Fork 361
Expand file tree
/
Copy pathclient_from.test.ts
More file actions
212 lines (193 loc) · 6.83 KB
/
Copy pathclient_from.test.ts
File metadata and controls
212 lines (193 loc) · 6.83 KB
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
204
205
206
207
208
209
210
211
212
import { describe, it, beforeEach, expect, vi } from "vitest";
import { concatUint8Arrays, stringToUint8Array } from "uint8array-extras";
import * as StellarSdk from "../../../src/index.js";
import { serverUrl } from "../../constants";
const { xdr, hash, Contract, rpc } = StellarSdk;
const { Client } = StellarSdk.contract;
const { Server } = rpc;
const networkPassphrase = "Test SDF Network ; September 2015";
// LEB128 unsigned varint, as used for WASM section lengths.
function leb128(value: number): Uint8Array {
const bytes: number[] = [];
let n = value;
do {
let byte = n & 0x7f;
n >>>= 7;
if (n !== 0) byte |= 0x80;
bytes.push(byte);
} while (n !== 0);
return Uint8Array.from(bytes);
}
// Builds a minimal valid WASM binary whose only content is a `contractspecv0`
// custom section carrying the given spec entries. This is browser-safe (pure
// Uint8Array ops, no filesystem) and is enough for `Spec.fromWasm` to parse,
// which only scans for that custom section.
function wasmWithSpec(entries: StellarSdk.xdr.ScSpecEntry[]): Uint8Array {
const name = stringToUint8Array("contractspecv0");
const payload = concatUint8Arrays(entries.map((e) => e.toXdr()));
const sectionBody = concatUint8Arrays([leb128(name.length), name, payload]);
const customSection = concatUint8Arrays([
Uint8Array.of(0x00), // custom section id
leb128(sectionBody.length),
sectionBody,
]);
const header = Uint8Array.of(
0x00,
0x61,
0x73,
0x6d, // "\0asm" magic
0x01,
0x00,
0x00,
0x00, // version 1
);
return concatUint8Arrays([header, customSection]);
}
describe("contract.Client.from", () => {
let server: any;
let mockPost: any;
// `Client.from` accepts a pre-built `Server` via `options.server`, so spying
// on that instance's http client lets the real code path
// (`getContractInstance`, then `getContractWasmByHash` for wasm contracts)
// run against controlled JSON-RPC responses without mocking a module.
beforeEach(() => {
server = new Server(serverUrl);
// The default throws rather than calling through: `vi.spyOn` keeps the real
// implementation, so once the queued `mockResolvedValueOnce` responses run
// out an unexpected call would otherwise issue a real HTTP request.
mockPost = vi.spyOn(server.httpClient, "post").mockImplementation(() => {
throw new Error("unexpected RPC call");
});
});
const contractId = "CCN57TGC6EXFCYIQJ4UCD2UDZ4C3AQCHVMK74DGZ3JYCA5HD4BY7FNPC";
const contract = new Contract(contractId);
const contractLedgerKey = contract.getFootprint();
const address = contract.address();
// Builds the JSON-RPC response shape returned by `getLedgerEntries` for a
// single ledger entry, matching what the RPC server produces.
function ledgerEntriesResponse(
val: StellarSdk.xdr.LedgerEntryData,
key: StellarSdk.xdr.LedgerKey,
) {
return {
data: {
result: {
latestLedger: 18039,
entries: [
{
liveUntilLedgerSeq: 1000,
lastModifiedLedgerSeq: 1,
xdr: val.toXdr("base64"),
key: key.toXdr("base64"),
},
],
},
},
};
}
describe("wasm contract (baseline)", () => {
// A synthetic wasm exposing a single `hello` function, so `Spec.fromWasm`
// can parse it. The wasm hash is arbitrary for the mock; it only has to
// match between the instance executable and the code entry.
const wasmBuffer = wasmWithSpec([
xdr.ScSpecEntry.scSpecEntryFunctionV0(
new xdr.ScSpecFunctionV0({
doc: "",
name: "hello",
inputs: [],
outputs: [],
}),
),
]);
const wasmHash = hash(wasmBuffer);
const instanceEntry = xdr.LedgerEntryData.contractData(
new xdr.ContractDataEntry({
ext: xdr.ExtensionPoint.v0(),
contract: address.toScAddress(),
durability: xdr.ContractDataDurability.persistent,
key: xdr.ScVal.scvLedgerKeyContractInstance(),
val: xdr.ScVal.scvContractInstance(
new xdr.ScContractInstance({
executable: xdr.ContractExecutable.contractExecutableWasm(wasmHash),
storage: null,
}),
),
}),
);
const wasmLedgerKey = xdr.LedgerKey.contractCode(
new xdr.LedgerKeyContractCode({ hash: wasmHash }),
);
const wasmLedgerCode = xdr.LedgerEntryData.contractCode(
new xdr.ContractCodeEntry({
ext: xdr.ContractCodeEntryExt.fromXdr(
"AAAAAQAAAAAAAAAAAAAVqAAAAJwAAAADAAAAAwAAABgAAAABAAAAAQAAABEAAAAgAAABpA==",
"base64",
),
hash: wasmHash,
code: wasmBuffer,
}),
);
it("builds a Client from a deployed wasm contract", async () => {
mockPost
.mockResolvedValueOnce(
ledgerEntriesResponse(instanceEntry, contractLedgerKey),
)
.mockResolvedValueOnce(
ledgerEntriesResponse(wasmLedgerCode, wasmLedgerKey),
);
const client = await Client.from({
contractId,
networkPassphrase,
rpcUrl: serverUrl,
server,
});
expect(client).toBeInstanceOf(Client);
expect(client.spec.funcs().length).toBeGreaterThan(0);
// The instance lookup, then the wasm fetch.
expect(mockPost).toHaveBeenCalledTimes(2);
});
});
describe("Stellar Asset Contract (SAC)", () => {
// A SAC's contract instance has a `StellarAsset` executable instead of a
// wasm hash, so there is no wasm to download from the network.
const sacInstanceEntry = xdr.LedgerEntryData.contractData(
new xdr.ContractDataEntry({
ext: xdr.ExtensionPoint.v0(),
contract: address.toScAddress(),
durability: xdr.ContractDataDurability.persistent,
key: xdr.ScVal.scvLedgerKeyContractInstance(),
val: xdr.ScVal.scvContractInstance(
new xdr.ScContractInstance({
executable: xdr.ContractExecutable.contractExecutableStellarAsset(),
storage: null,
}),
),
}),
);
it("builds a Client with the embedded SAC spec", async () => {
// Only the instance lookup is needed: a SAC has no wasm to fetch, so the
// embedded spec should be used instead of a second ledger-entries call.
mockPost.mockResolvedValueOnce(
ledgerEntriesResponse(sacInstanceEntry, contractLedgerKey),
);
const client = await Client.from({
contractId,
networkPassphrase,
rpcUrl: serverUrl,
server,
});
expect(client).toBeInstanceOf(Client);
// The standard token interface every SAC exposes.
for (const method of [
"symbol",
"name",
"decimals",
"balance",
"transfer",
]) {
expect(typeof (client as any)[method]).toBe("function");
}
expect(mockPost).toHaveBeenCalledTimes(1);
});
});
});