examples, tests: Setup prettier (#1152)

This commit is contained in:
Tom Linton 2021-12-16 12:11:41 +13:00 committed by GitHub
parent efd37219d2
commit 713d43668b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
40 changed files with 810 additions and 710 deletions

View File

@ -41,6 +41,10 @@ jobs:
- run: cd ts && yarn
- run: cd ts && yarn test
- run: cd ts && yarn lint
- run: cd examples/tutorial && yarn
- run: cd examples/tutorial && yarn lint
- run: cd tests && yarn
- run: cd tests && yarn lint
setup-anchor-cli:
name: Setup Anchor cli

View File

@ -2,7 +2,7 @@
// It is not expected users directly test with this example. For a more
// ergonomic example, see `tests/basic-0.js` in this workspace.
const anchor = require('@project-serum/anchor');
const anchor = require("@project-serum/anchor");
// Configure the local cluster.
anchor.setProvider(anchor.Provider.local());
@ -10,10 +10,12 @@ anchor.setProvider(anchor.Provider.local());
async function main() {
// #region main
// Read the generated IDL.
const idl = JSON.parse(require('fs').readFileSync('./target/idl/basic_0.json', 'utf8'));
const idl = JSON.parse(
require("fs").readFileSync("./target/idl/basic_0.json", "utf8")
);
// Address of the deployed program.
const programId = new anchor.web3.PublicKey('<YOUR-PROGRAM-ID>');
const programId = new anchor.web3.PublicKey("<YOUR-PROGRAM-ID>");
// Generate the program client from IDL.
const program = new anchor.Program(idl, programId);
@ -23,5 +25,5 @@ async function main() {
// #endregion main
}
console.log('Running client.');
main().then(() => console.log('Success'));
console.log("Running client.");
main().then(() => console.log("Success"));

View File

@ -1,20 +1,20 @@
const assert = require('assert');
const anchor = require('@project-serum/anchor');
const assert = require("assert");
const anchor = require("@project-serum/anchor");
const { SystemProgram } = anchor.web3;
describe('basic-2', () => {
const provider = anchor.Provider.local()
describe("basic-2", () => {
const provider = anchor.Provider.local();
// Configure the client to use the local cluster.
anchor.setProvider(provider)
anchor.setProvider(provider);
// Counter for the tests.
const counter = anchor.web3.Keypair.generate()
const counter = anchor.web3.Keypair.generate();
// Program for the tests.
const program = anchor.workspace.Basic2
const program = anchor.workspace.Basic2;
it('Creates a counter', async () => {
it("Creates a counter", async () => {
await program.rpc.create(provider.wallet.publicKey, {
accounts: {
counter: counter.publicKey,
@ -22,25 +22,27 @@ describe('basic-2', () => {
systemProgram: SystemProgram.programId,
},
signers: [counter],
})
});
let counterAccount = await program.account.counter.fetch(counter.publicKey)
let counterAccount = await program.account.counter.fetch(counter.publicKey);
assert.ok(counterAccount.authority.equals(provider.wallet.publicKey))
assert.ok(counterAccount.count.toNumber() === 0)
})
assert.ok(counterAccount.authority.equals(provider.wallet.publicKey));
assert.ok(counterAccount.count.toNumber() === 0);
});
it('Updates a counter', async () => {
it("Updates a counter", async () => {
await program.rpc.increment({
accounts: {
counter: counter.publicKey,
authority: provider.wallet.publicKey,
},
})
});
const counterAccount = await program.account.counter.fetch(counter.publicKey)
const counterAccount = await program.account.counter.fetch(
counter.publicKey
);
assert.ok(counterAccount.authority.equals(provider.wallet.publicKey))
assert.ok(counterAccount.count.toNumber() == 1)
})
})
assert.ok(counterAccount.authority.equals(provider.wallet.publicKey));
assert.ok(counterAccount.count.toNumber() == 1);
});
});

View File

@ -25,10 +25,10 @@ describe("basic-3", () => {
// Invoke the puppet master to perform a CPI to the puppet.
await puppetMaster.rpc.pullStrings(new anchor.BN(111), {
accounts: {
puppet: newPuppetAccount.publicKey,
puppetProgram: puppet.programId,
},
accounts: {
puppet: newPuppetAccount.publicKey,
puppetProgram: puppet.programId,
},
});
// Check the state updated.

View File

@ -1,6 +1,10 @@
{
"name": "anchor-examples",
"private": true,
"scripts": {
"lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w",
"lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check"
},
"workspaces": [
"basic-0",
"basic-1",
@ -12,6 +16,7 @@
"@project-serum/anchor": "^0.19.0"
},
"devDependencies": {
"mocha": "^9.1.3"
"mocha": "^9.1.3",
"prettier": "^2.5.1"
}
}

View File

@ -30,17 +30,17 @@
"@ethersproject/logger" "^5.5.0"
hash.js "1.1.7"
"@project-serum/anchor@^0.18.0":
version "0.18.0"
resolved "https://registry.yarnpkg.com/@project-serum/anchor/-/anchor-0.18.0.tgz#867144282e59482230f797f73ee9f5634f846061"
integrity sha512-WTm+UB93MoxyCbjnHIibv/uUEoO/5gL4GEtE/aMioLF8Z4i0vCMPnvAN0xpk9VBu3t7ld2DcCE/L+6Z7dwU++w==
"@project-serum/anchor@^0.19.0":
version "0.19.0"
resolved "https://registry.yarnpkg.com/@project-serum/anchor/-/anchor-0.19.0.tgz#79f1fbe7c3134860ccbfe458a0e09daf79644885"
integrity sha512-cs0LBmJOrL9eJ8MRNqitnzbpCT5QEzVdJmiIjfNV5YaGn1K9vISR7DtISj3Bdl3KBdLqii4CTw1mpHdi8iXUCg==
dependencies:
"@project-serum/borsh" "^0.2.2"
"@solana/web3.js" "^1.17.0"
base64-js "^1.5.1"
bn.js "^5.1.2"
bs58 "^4.0.1"
buffer-layout "^1.2.0"
buffer-layout "^1.2.2"
camelcase "^5.3.1"
crypto-hash "^1.3.0"
eventemitter3 "^4.0.7"
@ -257,7 +257,7 @@ bs58@^4.0.0, bs58@^4.0.1:
dependencies:
base-x "^3.0.2"
buffer-layout@^1.2.0:
buffer-layout@^1.2.0, buffer-layout@^1.2.2:
version "1.2.2"
resolved "https://registry.yarnpkg.com/buffer-layout/-/buffer-layout-1.2.2.tgz#b9814e7c7235783085f9ca4966a0cfff112259d5"
integrity sha512-kWSuLN694+KTk8SrYvCqwP2WcgQjoRCiF5b4QDvkkz8EmgD+aWAIceGFKMIAdmF/pH+vpgNV3d3kAKorcdAmWA==
@ -812,6 +812,11 @@ picomatch@^2.0.4, picomatch@^2.2.1:
resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-2.3.0.tgz#f1f061de8f6a4bf022892e2d128234fb98302972"
integrity sha512-lY1Q/PiJGC2zOv/z391WOTD+Z02bCgsFfvxoXXf6h7kv9o+WmsmzYqrAwY63sNgOxE4xEdq0WyUnXfKeBrSvYw==
prettier@^2.5.1:
version "2.5.1"
resolved "https://registry.yarnpkg.com/prettier/-/prettier-2.5.1.tgz#fff75fa9d519c54cf0fce328c1017d94546bc56a"
integrity sha512-vBZcPRUR5MZJwoyi3ZoyQlc1rXeEck8KgeC9AwwOn+exuxLxq5toTRDTSaVrXHxelDMHy9zlicw8u66yxoSUFg==
randombytes@^2.1.0:
version "2.1.0"
resolved "https://registry.yarnpkg.com/randombytes/-/randombytes-2.1.0.tgz#df6f84372f0270dc65cdf6291349ab7a473d4f2a"

2
tests/.prettierignore Normal file
View File

@ -0,0 +1,2 @@
**/target/types/*.ts
cfo/deps/

View File

@ -9,4 +9,4 @@ module.exports = async function (provider) {
anchor.setProvider(provider);
// Add your deploy script here.
}
};

View File

@ -1,22 +1,23 @@
import * as anchor from '@project-serum/anchor';
import { Program } from '@project-serum/anchor';
import { findProgramAddressSync } from '@project-serum/anchor/dist/cjs/utils/pubkey';
import { PublicKey } from '@solana/web3.js';
import assert from 'assert';
import { BpfUpgradeableState } from '../target/types/bpf_upgradeable_state';
import * as anchor from "@project-serum/anchor";
import { Program } from "@project-serum/anchor";
import { findProgramAddressSync } from "@project-serum/anchor/dist/cjs/utils/pubkey";
import { PublicKey } from "@solana/web3.js";
import assert from "assert";
import { BpfUpgradeableState } from "../target/types/bpf_upgradeable_state";
describe('bpf_upgradeable_state', () => {
describe("bpf_upgradeable_state", () => {
const provider = anchor.Provider.env();
// Configure the client to use the local cluster.
anchor.setProvider(provider);
const program = anchor.workspace.BpfUpgradeableState as Program<BpfUpgradeableState>;
const program = anchor.workspace
.BpfUpgradeableState as Program<BpfUpgradeableState>;
const programDataAddress = findProgramAddressSync(
[program.programId.toBytes()],
new anchor.web3.PublicKey("BPFLoaderUpgradeab1e11111111111111111111111")
)[0];
it('Reads ProgramData and sets field', async () => {
it("Reads ProgramData and sets field", async () => {
const settings = anchor.web3.Keypair.generate();
const tx = await program.rpc.setAdminSettings(new anchor.BN(500), {
accounts: {
@ -24,34 +25,46 @@ describe('bpf_upgradeable_state', () => {
systemProgram: anchor.web3.SystemProgram.programId,
programData: programDataAddress,
program: program.programId,
settings: settings.publicKey
settings: settings.publicKey,
},
signers: [settings]
signers: [settings],
});
assert.equal((await program.account.settings.fetch(settings.publicKey)).adminData, 500);
assert.equal(
(await program.account.settings.fetch(settings.publicKey)).adminData,
500
);
});
it('Reads ProgramData and sets field, uses program state', async () => {
it("Reads ProgramData and sets field, uses program state", async () => {
const settings = anchor.web3.Keypair.generate();
const tx = await program.rpc.setAdminSettingsUseProgramState(new anchor.BN(500), {
accounts: {
authority: program.provider.wallet.publicKey,
systemProgram: anchor.web3.SystemProgram.programId,
programData: programDataAddress,
program: program.programId,
settings: settings.publicKey
},
signers: [settings]
});
assert.equal((await program.account.settings.fetch(settings.publicKey)).adminData, 500);
const tx = await program.rpc.setAdminSettingsUseProgramState(
new anchor.BN(500),
{
accounts: {
authority: program.provider.wallet.publicKey,
systemProgram: anchor.web3.SystemProgram.programId,
programData: programDataAddress,
program: program.programId,
settings: settings.publicKey,
},
signers: [settings],
}
);
assert.equal(
(await program.account.settings.fetch(settings.publicKey)).adminData,
500
);
});
it('Validates constraint on ProgramData', async () => {
it("Validates constraint on ProgramData", async () => {
const settings = anchor.web3.Keypair.generate();
try {
const authority = anchor.web3.Keypair.generate();
await provider.connection.confirmTransaction(
await provider.connection.requestAirdrop(authority.publicKey, 10000000000),
await provider.connection.requestAirdrop(
authority.publicKey,
10000000000
),
"confirmed"
);
await program.rpc.setAdminSettings(new anchor.BN(500), {
@ -62,7 +75,7 @@ describe('bpf_upgradeable_state', () => {
settings: settings.publicKey,
program: program.programId,
},
signers: [settings, authority]
signers: [settings, authority],
});
assert.ok(false);
} catch (err) {
@ -71,7 +84,7 @@ describe('bpf_upgradeable_state', () => {
}
});
it('Validates that account is ProgramData', async () => {
it("Validates that account is ProgramData", async () => {
const settings = anchor.web3.Keypair.generate();
try {
await program.rpc.setAdminSettings(new anchor.BN(500), {
@ -82,7 +95,7 @@ describe('bpf_upgradeable_state', () => {
settings: settings.publicKey,
program: program.programId,
},
signers: [settings]
signers: [settings],
});
assert.ok(false);
} catch (err) {
@ -91,7 +104,7 @@ describe('bpf_upgradeable_state', () => {
}
});
it('Validates that account is owned by the upgradeable bpf loader', async () => {
it("Validates that account is owned by the upgradeable bpf loader", async () => {
const settings = anchor.web3.Keypair.generate();
try {
await program.rpc.setAdminSettings(new anchor.BN(500), {
@ -102,17 +115,22 @@ describe('bpf_upgradeable_state', () => {
settings: settings.publicKey,
program: program.programId,
},
signers: [settings]
signers: [settings],
});
assert.ok(false);
} catch (err) {
assert.equal(err.code, 3007);
assert.equal(err.msg, "The given account is not owned by the executing program");
assert.equal(
err.msg,
"The given account is not owned by the executing program"
);
}
});
it('Deserializes UpgradableLoaderState and validates that programData is the expected account', async () => {
const secondProgramAddress = new PublicKey("Fkv67TwmbakfZw2PoW57wYPbqNexAH6vuxpyT8vmrc3B");
it("Deserializes UpgradableLoaderState and validates that programData is the expected account", async () => {
const secondProgramAddress = new PublicKey(
"Fkv67TwmbakfZw2PoW57wYPbqNexAH6vuxpyT8vmrc3B"
);
const secondProgramProgramDataAddress = findProgramAddressSync(
[secondProgramAddress.toBytes()],
new anchor.web3.PublicKey("BPFLoaderUpgradeab1e11111111111111111111111")
@ -128,7 +146,7 @@ describe('bpf_upgradeable_state', () => {
settings: settings.publicKey,
program: program.programId,
},
signers: [settings]
signers: [settings],
});
assert.ok(false);
} catch (err) {
@ -136,8 +154,10 @@ describe('bpf_upgradeable_state', () => {
}
});
it('Deserializes Program and validates that programData is the expected account', async () => {
const secondProgramAddress = new PublicKey("Fkv67TwmbakfZw2PoW57wYPbqNexAH6vuxpyT8vmrc3B");
it("Deserializes Program and validates that programData is the expected account", async () => {
const secondProgramAddress = new PublicKey(
"Fkv67TwmbakfZw2PoW57wYPbqNexAH6vuxpyT8vmrc3B"
);
const secondProgramProgramDataAddress = findProgramAddressSync(
[secondProgramAddress.toBytes()],
new anchor.web3.PublicKey("BPFLoaderUpgradeab1e11111111111111111111111")
@ -153,7 +173,7 @@ describe('bpf_upgradeable_state', () => {
settings: settings.publicKey,
program: program.programId,
},
signers: [settings]
signers: [settings],
});
assert.ok(false);
} catch (err) {

View File

@ -1,4 +1,3 @@
// Migrations are an early feature. Currently, they're nothing more than this
// single deploy script that's invoked from the CLI, injecting a provider
// configured from the workspace's Anchor.toml.
@ -10,4 +9,4 @@ module.exports = async function (provider) {
anchor.setProvider(provider);
// Add your deploy script here.
}
};

View File

@ -3,8 +3,6 @@ const serumCmn = require("@project-serum/common");
const assert = require("assert");
const { TOKEN_PROGRAM_ID } = require("@solana/spl-token");
describe("cashiers-check", () => {
// Configure the client to use the local cluster.
anchor.setProvider(anchor.Provider.env());

View File

@ -1,4 +1,3 @@
// Migrations are an early feature. Currently, they're nothing more than this
// single deploy script that's invoked from the CLI, injecting a provider
// configured from the workspace's Anchor.toml.
@ -10,4 +9,4 @@ module.exports = async function (provider) {
anchor.setProvider(provider);
// Add your deploy script here.
}
};

View File

@ -206,43 +206,39 @@ async function setupMarket({
);
for (let k = 0; k < asks.length; k += 1) {
let ask = asks[k];
const {
transaction,
signers,
} = await MARKET_A_USDC.makePlaceOrderTransaction(provider.connection, {
owner: marketMaker.account,
payer: marketMaker.baseToken,
side: "sell",
price: ask[0],
size: ask[1],
orderType: "postOnly",
clientId: undefined,
openOrdersAddressKey: undefined,
openOrdersAccount: undefined,
feeDiscountPubkey: null,
selfTradeBehavior: "abortTransaction",
});
const { transaction, signers } =
await MARKET_A_USDC.makePlaceOrderTransaction(provider.connection, {
owner: marketMaker.account,
payer: marketMaker.baseToken,
side: "sell",
price: ask[0],
size: ask[1],
orderType: "postOnly",
clientId: undefined,
openOrdersAddressKey: undefined,
openOrdersAccount: undefined,
feeDiscountPubkey: null,
selfTradeBehavior: "abortTransaction",
});
await provider.send(transaction, signers.concat(marketMaker.account));
}
for (let k = 0; k < bids.length; k += 1) {
let bid = bids[k];
const {
transaction,
signers,
} = await MARKET_A_USDC.makePlaceOrderTransaction(provider.connection, {
owner: marketMaker.account,
payer: marketMaker.quoteToken,
side: "buy",
price: bid[0],
size: bid[1],
orderType: "postOnly",
clientId: undefined,
openOrdersAddressKey: undefined,
openOrdersAccount: undefined,
feeDiscountPubkey: null,
selfTradeBehavior: "abortTransaction",
});
const { transaction, signers } =
await MARKET_A_USDC.makePlaceOrderTransaction(provider.connection, {
owner: marketMaker.account,
payer: marketMaker.quoteToken,
side: "buy",
price: bid[0],
size: bid[1],
orderType: "postOnly",
clientId: undefined,
openOrdersAddressKey: undefined,
openOrdersAccount: undefined,
feeDiscountPubkey: null,
selfTradeBehavior: "abortTransaction",
});
await provider.send(transaction, signers.concat(marketMaker.account));
}
@ -516,42 +512,38 @@ async function runTradeBot(market, provider, iterations = undefined) {
}
// Post ask.
const {
transaction: tx_ask,
signers: sigs_ask,
} = await marketClient.makePlaceOrderTransaction(provider.connection, {
owner: maker,
payer: baseToken,
side: "sell",
price,
size,
orderType: "postOnly",
clientId,
openOrdersAddressKey: undefined,
openOrdersAccount: undefined,
feeDiscountPubkey: null,
selfTradeBehavior: "abortTransaction",
});
const { transaction: tx_ask, signers: sigs_ask } =
await marketClient.makePlaceOrderTransaction(provider.connection, {
owner: maker,
payer: baseToken,
side: "sell",
price,
size,
orderType: "postOnly",
clientId,
openOrdersAddressKey: undefined,
openOrdersAccount: undefined,
feeDiscountPubkey: null,
selfTradeBehavior: "abortTransaction",
});
let txSig = await provider.send(tx_ask, sigs_ask.concat(maker));
console.log("Ask", txSig);
// Take.
const {
transaction: tx_bid,
signers: sigs_bid,
} = await marketClient.makePlaceOrderTransaction(provider.connection, {
owner: taker,
payer: quoteToken,
side: "buy",
price,
size,
orderType: "ioc",
clientId: undefined,
openOrdersAddressKey: undefined,
openOrdersAccount: undefined,
feeDiscountPubkey: null,
selfTradeBehavior: "abortTransaction",
});
const { transaction: tx_bid, signers: sigs_bid } =
await marketClient.makePlaceOrderTransaction(provider.connection, {
owner: taker,
payer: quoteToken,
side: "buy",
price,
size,
orderType: "ioc",
clientId: undefined,
openOrdersAddressKey: undefined,
openOrdersAccount: undefined,
feeDiscountPubkey: null,
selfTradeBehavior: "abortTransaction",
});
txSig = await provider.send(tx_bid, sigs_bid.concat(taker));
console.log("Bid", txSig);

View File

@ -32,13 +32,11 @@ const WHITELIST_SIZE = 10;
async function setupStakePool(mint, god) {
// Registry genesis.
const [
_registrarSigner,
_nonce,
] = await anchor.web3.PublicKey.findProgramAddress(
[registrar.publicKey.toBuffer()],
registry.programId
);
const [_registrarSigner, _nonce] =
await anchor.web3.PublicKey.findProgramAddress(
[registrar.publicKey.toBuffer()],
registry.programId
);
registrarSigner = _registrarSigner;
nonce = _nonce;
poolMint = await serumCmn.createMint(provider, registrarSigner);
@ -96,13 +94,11 @@ async function setupStakePool(mint, god) {
seed,
registry.programId
);
const [
_memberSigner,
nonce2,
] = await anchor.web3.PublicKey.findProgramAddress(
[registrar.publicKey.toBuffer(), member.toBuffer()],
registry.programId
);
const [_memberSigner, nonce2] =
await anchor.web3.PublicKey.findProgramAddress(
[registrar.publicKey.toBuffer(), member.toBuffer()],
registry.programId
);
memberSigner = _memberSigner;
const [mainTx, _balances] = await utils.createBalanceSandbox(
provider,
@ -133,9 +129,10 @@ async function setupStakePool(mint, god) {
newAccountPubkey: member,
basePubkey: registry.provider.wallet.publicKey,
seed,
lamports: await registry.provider.connection.getMinimumBalanceForRentExemption(
registry.account.member.size
),
lamports:
await registry.provider.connection.getMinimumBalanceForRentExemption(
registry.account.member.size
),
space: registry.account.member.size,
programId: registry.programId,
}),

View File

@ -9,4 +9,4 @@ module.exports = async function (provider) {
anchor.setProvider(provider);
// Add your deploy script here.
}
};

View File

@ -1,5 +1,5 @@
const assert = require("assert");
const anchor = require('@project-serum/anchor');
const anchor = require("@project-serum/anchor");
const { Account, Transaction, TransactionInstruction } = anchor.web3;
describe("errors", () => {
@ -133,12 +133,15 @@ describe("errors", () => {
try {
const tx = await program.rpc.accountNotInitializedError({
accounts: {
notInitializedAccount: (new anchor.web3.Keypair()).publicKey
notInitializedAccount: new anchor.web3.Keypair().publicKey,
},
});
assert.fail("Unexpected success in creating a transaction that should have fail with `AccountNotInitialized` error");
assert.fail(
"Unexpected success in creating a transaction that should have fail with `AccountNotInitialized` error"
);
} catch (err) {
const errMsg = "The program expected this account to be already initialized";
const errMsg =
"The program expected this account to be already initialized";
assert.equal(err.toString(), errMsg);
}
});

View File

@ -9,4 +9,4 @@ module.exports = async function (provider) {
anchor.setProvider(provider);
// Add your deploy script here.
}
};

View File

@ -9,4 +9,4 @@ module.exports = async function (provider) {
anchor.setProvider(provider);
// Add your deploy script here.
}
};

View File

@ -53,7 +53,7 @@ describe("ido-pool", () => {
idoAuthorityWatermelon,
provider.wallet.publicKey,
[],
watermelonIdoAmount.toString(),
watermelonIdoAmount.toString()
);
idoAuthority_watermelon_account = await getTokenAccount(
provider,
@ -62,7 +62,7 @@ describe("ido-pool", () => {
assert.ok(idoAuthority_watermelon_account.amount.eq(watermelonIdoAmount));
});
// These are all variables the client will need to create in order to
// These are all variables the client will need to create in order to
// initialize the IDO pool
let idoTimes;
let idoName = "test_ido";
@ -70,28 +70,32 @@ describe("ido-pool", () => {
it("Initializes the IDO pool", async () => {
let bumps = new PoolBumps();
const [idoAccount, idoAccountBump] = await anchor.web3.PublicKey.findProgramAddress(
[Buffer.from(idoName)],
program.programId
);
const [idoAccount, idoAccountBump] =
await anchor.web3.PublicKey.findProgramAddress(
[Buffer.from(idoName)],
program.programId
);
bumps.idoAccount = idoAccountBump;
const [redeemableMint, redeemableMintBump] = await anchor.web3.PublicKey.findProgramAddress(
[Buffer.from(idoName), Buffer.from("redeemable_mint")],
program.programId
);
const [redeemableMint, redeemableMintBump] =
await anchor.web3.PublicKey.findProgramAddress(
[Buffer.from(idoName), Buffer.from("redeemable_mint")],
program.programId
);
bumps.redeemableMint = redeemableMintBump;
const [poolWatermelon, poolWatermelonBump] = await anchor.web3.PublicKey.findProgramAddress(
[Buffer.from(idoName), Buffer.from("pool_watermelon")],
program.programId
);
const [poolWatermelon, poolWatermelonBump] =
await anchor.web3.PublicKey.findProgramAddress(
[Buffer.from(idoName), Buffer.from("pool_watermelon")],
program.programId
);
bumps.poolWatermelon = poolWatermelonBump;
const [poolUsdc, poolUsdcBump] = await anchor.web3.PublicKey.findProgramAddress(
[Buffer.from(idoName), Buffer.from("pool_usdc")],
program.programId
);
const [poolUsdc, poolUsdcBump] =
await anchor.web3.PublicKey.findProgramAddress(
[Buffer.from(idoName), Buffer.from("pool_usdc")],
program.programId
);
bumps.poolUsdc = poolUsdcBump;
idoTimes = new IdoTimes();
@ -171,15 +175,17 @@ describe("ido-pool", () => {
usdcMint,
userUsdc,
program.provider.wallet.publicKey,
program.provider.wallet.publicKey,
)
let createUserUsdcTrns = new anchor.web3.Transaction().add(createUserUsdcInstr);
program.provider.wallet.publicKey
);
let createUserUsdcTrns = new anchor.web3.Transaction().add(
createUserUsdcInstr
);
await provider.send(createUserUsdcTrns);
await usdcMintAccount.mintTo(
userUsdc,
provider.wallet.publicKey,
[],
firstDeposit.toString(),
firstDeposit.toString()
);
// Check if we inited correctly
@ -187,9 +193,11 @@ describe("ido-pool", () => {
assert.ok(userUsdcAccount.amount.eq(firstDeposit));
const [userRedeemable] = await anchor.web3.PublicKey.findProgramAddress(
[provider.wallet.publicKey.toBuffer(),
Buffer.from(idoName),
Buffer.from("user_redeemable")],
[
provider.wallet.publicKey.toBuffer(),
Buffer.from(idoName),
Buffer.from("user_redeemable"),
],
program.programId
);
@ -216,9 +224,9 @@ describe("ido-pool", () => {
systemProgram: anchor.web3.SystemProgram.programId,
tokenProgram: TOKEN_PROGRAM_ID,
rent: anchor.web3.SYSVAR_RENT_PUBKEY,
}
})
]
},
}),
],
});
} catch (err) {
console.log("This is the error message", err.toString());
@ -254,14 +262,14 @@ describe("ido-pool", () => {
transferSolInstr = anchor.web3.SystemProgram.transfer({
fromPubkey: provider.wallet.publicKey,
lamports: 100_000_000_000, // 100 sol
toPubkey: secondUserKeypair.publicKey
toPubkey: secondUserKeypair.publicKey,
});
secondUserUsdc = await Token.getAssociatedTokenAddress(
ASSOCIATED_TOKEN_PROGRAM_ID,
TOKEN_PROGRAM_ID,
usdcMint,
secondUserKeypair.publicKey
)
);
createSecondUserUsdcInstr = Token.createAssociatedTokenAccountInstruction(
ASSOCIATED_TOKEN_PROGRAM_ID,
TOKEN_PROGRAM_ID,
@ -278,19 +286,22 @@ describe("ido-pool", () => {
secondUserUsdc,
provider.wallet.publicKey,
[],
secondDeposit.toString(),
)
secondDeposit.toString()
);
// Checking the transfer went through
secondUserUsdcAccount = await getTokenAccount(provider, secondUserUsdc);
assert.ok(secondUserUsdcAccount.amount.eq(secondDeposit));
const [secondUserRedeemable] = await anchor.web3.PublicKey.findProgramAddress(
[secondUserKeypair.publicKey.toBuffer(),
Buffer.from(idoName),
Buffer.from("user_redeemable")],
program.programId
);
const [secondUserRedeemable] =
await anchor.web3.PublicKey.findProgramAddress(
[
secondUserKeypair.publicKey.toBuffer(),
Buffer.from(idoName),
Buffer.from("user_redeemable"),
],
program.programId
);
await program.rpc.exchangeUsdcForRedeemable(secondDeposit, {
accounts: {
@ -315,9 +326,9 @@ describe("ido-pool", () => {
tokenProgram: TOKEN_PROGRAM_ID,
rent: anchor.web3.SYSVAR_RENT_PUBKEY,
},
})
}),
],
signers: [secondUserKeypair]
signers: [secondUserKeypair],
});
secondUserRedeemableAccount = await getTokenAccount(
@ -329,7 +340,6 @@ describe("ido-pool", () => {
totalPoolUsdc = firstDeposit.add(secondDeposit);
poolUsdcAccount = await getTokenAccount(provider, poolUsdc);
assert.ok(poolUsdcAccount.amount.eq(totalPoolUsdc));
});
const firstWithdrawal = new anchor.BN(2_000_000);
@ -351,16 +361,20 @@ describe("ido-pool", () => {
);
const [userRedeemable] = await anchor.web3.PublicKey.findProgramAddress(
[provider.wallet.publicKey.toBuffer(),
Buffer.from(idoName),
Buffer.from("user_redeemable")],
[
provider.wallet.publicKey.toBuffer(),
Buffer.from(idoName),
Buffer.from("user_redeemable"),
],
program.programId
);
const [escrowUsdc] = await anchor.web3.PublicKey.findProgramAddress(
[provider.wallet.publicKey.toBuffer(),
Buffer.from(idoName),
Buffer.from("escrow_usdc")],
[
provider.wallet.publicKey.toBuffer(),
Buffer.from(idoName),
Buffer.from("escrow_usdc"),
],
program.programId
);
@ -385,10 +399,10 @@ describe("ido-pool", () => {
usdcMint,
systemProgram: anchor.web3.SystemProgram.programId,
tokenProgram: TOKEN_PROGRAM_ID,
rent: anchor.web3.SYSVAR_RENT_PUBKEY
}
})
]
rent: anchor.web3.SYSVAR_RENT_PUBKEY,
},
}),
],
});
totalPoolUsdc = totalPoolUsdc.sub(firstWithdrawal);
@ -420,9 +434,11 @@ describe("ido-pool", () => {
);
const [userRedeemable] = await anchor.web3.PublicKey.findProgramAddress(
[provider.wallet.publicKey.toBuffer(),
Buffer.from(idoName),
Buffer.from("user_redeemable")],
[
provider.wallet.publicKey.toBuffer(),
Buffer.from(idoName),
Buffer.from("user_redeemable"),
],
program.programId
);
@ -469,12 +485,15 @@ describe("ido-pool", () => {
program.programId
);
const [secondUserRedeemable] = await anchor.web3.PublicKey.findProgramAddress(
[secondUserKeypair.publicKey.toBuffer(),
Buffer.from(idoName),
Buffer.from("user_redeemable")],
program.programId
);
const [secondUserRedeemable] =
await anchor.web3.PublicKey.findProgramAddress(
[
secondUserKeypair.publicKey.toBuffer(),
Buffer.from(idoName),
Buffer.from("user_redeemable"),
],
program.programId
);
const [poolWatermelon] = await anchor.web3.PublicKey.findProgramAddress(
[Buffer.from(idoName), Buffer.from("pool_watermelon")],
@ -509,7 +528,7 @@ describe("ido-pool", () => {
const [idoAccount] = await anchor.web3.PublicKey.findProgramAddress(
[Buffer.from(idoName)],
program.programId
)
);
const [poolUsdc] = await anchor.web3.PublicKey.findProgramAddress(
[Buffer.from(idoName), Buffer.from("pool_usdc")],
@ -546,9 +565,11 @@ describe("ido-pool", () => {
);
const [escrowUsdc] = await anchor.web3.PublicKey.findProgramAddress(
[provider.wallet.publicKey.toBuffer(),
Buffer.from(idoName),
Buffer.from("escrow_usdc")],
[
provider.wallet.publicKey.toBuffer(),
Buffer.from(idoName),
Buffer.from("escrow_usdc"),
],
program.programId
);
@ -561,25 +582,24 @@ describe("ido-pool", () => {
idoAccount,
usdcMint,
tokenProgram: TOKEN_PROGRAM_ID,
}
},
});
userUsdcAccount = await getTokenAccount(provider, userUsdc);
assert.ok(userUsdcAccount.amount.eq(firstWithdrawal));
});
function PoolBumps() {
this.idoAccount;
this.redeemableMint;
this.poolWatermelon;
this.poolUsdc;
};
}
function IdoTimes() {
this.startIdo;
this.endDeposts;
this.endIdo;
this.endEscrow;
};
}
});

View File

@ -1,4 +1,4 @@
const anchor = require('@project-serum/anchor');
const anchor = require("@project-serum/anchor");
const assert = require("assert");
describe("interface", () => {

View File

@ -31,7 +31,7 @@ module.exports = async function (provider) {
});
// Delete the default whitelist entries.
const defaultEntry = { programId: new anchor.web3.PublicKey.default };
const defaultEntry = { programId: new anchor.web3.PublicKey.default() };
await lockup.state.rpc.whitelistDelete(defaultEntry, {
accounts: {
authority: provider.wallet.publicKey,
@ -143,13 +143,11 @@ async function registrarInit(
const rewardQ = anchor.web3.Keypair.generate();
const withdrawalTimelock = new anchor.BN(_withdrawalTimelock);
const stakeRate = new anchor.BN(_stakeRate);
const [
registrarSigner,
nonce,
] = await anchor.web3.PublicKey.findProgramAddress(
[registrar.publicKey.toBuffer()],
registry.programId
);
const [registrarSigner, nonce] =
await anchor.web3.PublicKey.findProgramAddress(
[registrar.publicKey.toBuffer()],
registry.programId
);
const poolMint = await serumCmn.createMint(
registry.provider,
registrarSigner

View File

@ -4,7 +4,7 @@ const serumCmn = require("@project-serum/common");
const { TOKEN_PROGRAM_ID } = require("@solana/spl-token");
const utils = require("./utils");
anchor.utils.features.set('anchor-deprecated-state');
anchor.utils.features.set("anchor-deprecated-state");
describe("Lockup and Registry", () => {
// Read the provider from the configured environmnet.
@ -147,13 +147,11 @@ describe("Lockup and Registry", () => {
const depositAmount = new anchor.BN(100);
const vault = anchor.web3.Keypair.generate();
let [
_vestingSigner,
nonce,
] = await anchor.web3.PublicKey.findProgramAddress(
[vesting.publicKey.toBuffer()],
lockup.programId
);
let [_vestingSigner, nonce] =
await anchor.web3.PublicKey.findProgramAddress(
[vesting.publicKey.toBuffer()],
lockup.programId
);
vestingSigner = _vestingSigner;
await lockup.rpc.createVesting(
@ -272,13 +270,11 @@ describe("Lockup and Registry", () => {
let poolMint = null;
it("Creates registry genesis", async () => {
const [
_registrarSigner,
_nonce,
] = await anchor.web3.PublicKey.findProgramAddress(
[registrar.publicKey.toBuffer()],
registry.programId
);
const [_registrarSigner, _nonce] =
await anchor.web3.PublicKey.findProgramAddress(
[registrar.publicKey.toBuffer()],
registry.programId
);
registrarSigner = _registrarSigner;
nonce = _nonce;
poolMint = await serumCmn.createMint(provider, registrarSigner);
@ -326,7 +322,9 @@ describe("Lockup and Registry", () => {
}
);
registrarAccount = await registry.account.registrar.fetch(registrar.publicKey);
registrarAccount = await registry.account.registrar.fetch(
registrar.publicKey
);
assert.ok(registrarAccount.authority.equals(provider.wallet.publicKey));
assert.equal(registrarAccount.nonce, nonce);
@ -344,13 +342,11 @@ describe("Lockup and Registry", () => {
let balancesLocked = null;
it("Creates a member", async () => {
const [
_memberSigner,
nonce,
] = await anchor.web3.PublicKey.findProgramAddress(
[registrar.publicKey.toBuffer(), member.publicKey.toBuffer()],
registry.programId
);
const [_memberSigner, nonce] =
await anchor.web3.PublicKey.findProgramAddress(
[registrar.publicKey.toBuffer(), member.publicKey.toBuffer()],
registry.programId
);
memberSigner = _memberSigner;
const [mainTx, _balances] = await utils.createBalanceSandbox(
@ -474,13 +470,11 @@ describe("Lockup and Registry", () => {
};
const rewardAmount = new anchor.BN(200);
const expiry = new anchor.BN(Date.now() / 1000 + 5);
const [
_vendorSigner,
nonce,
] = await anchor.web3.PublicKey.findProgramAddress(
[registrar.publicKey.toBuffer(), unlockedVendor.publicKey.toBuffer()],
registry.programId
);
const [_vendorSigner, nonce] =
await anchor.web3.PublicKey.findProgramAddress(
[registrar.publicKey.toBuffer(), unlockedVendor.publicKey.toBuffer()],
registry.programId
);
unlockedVendorSigner = _vendorSigner;
await registry.rpc.dropReward(
@ -593,13 +587,11 @@ describe("Lockup and Registry", () => {
};
lockedRewardAmount = new anchor.BN(200);
const expiry = new anchor.BN(Date.now() / 1000 + 5);
const [
_vendorSigner,
nonce,
] = await anchor.web3.PublicKey.findProgramAddress(
[registrar.publicKey.toBuffer(), lockedVendor.publicKey.toBuffer()],
registry.programId
);
const [_vendorSigner, nonce] =
await anchor.web3.PublicKey.findProgramAddress(
[registrar.publicKey.toBuffer(), lockedVendor.publicKey.toBuffer()],
registry.programId
);
lockedVendorSigner = _vendorSigner;
await registry.rpc.dropReward(
@ -672,13 +664,11 @@ describe("Lockup and Registry", () => {
it("Claims a locked reward", async () => {
vendoredVesting = anchor.web3.Keypair.generate();
vendoredVestingVault = anchor.web3.Keypair.generate();
let [
_vendoredVestingSigner,
nonce,
] = await anchor.web3.PublicKey.findProgramAddress(
[vendoredVesting.publicKey.toBuffer()],
lockup.programId
);
let [_vendoredVestingSigner, nonce] =
await anchor.web3.PublicKey.findProgramAddress(
[vendoredVesting.publicKey.toBuffer()],
lockup.programId
);
vendoredVestingSigner = _vendoredVestingSigner;
const remainingAccounts = lockup.instruction.createVesting
.accounts({

View File

@ -1,4 +1,3 @@
// Migrations are an early feature. Currently, they're nothing more than this
// single deploy script that's invoked from the CLI, injecting a provider
// configured from the workspace's Anchor.toml.
@ -10,4 +9,4 @@ module.exports = async function (provider) {
anchor.setProvider(provider);
// Add your deploy script here.
}
};

View File

@ -736,11 +736,12 @@ describe("misc", () => {
]);
// Call for multiple kinds of .all.
const allAccounts = await program.account.dataWithFilter.all();
const allAccountsFilteredByBuffer = await program.account.dataWithFilter.all(
program.provider.wallet.publicKey.toBuffer()
);
const allAccountsFilteredByProgramFilters1 = await program.account.dataWithFilter.all(
[
const allAccountsFilteredByBuffer =
await program.account.dataWithFilter.all(
program.provider.wallet.publicKey.toBuffer()
);
const allAccountsFilteredByProgramFilters1 =
await program.account.dataWithFilter.all([
{
memcmp: {
offset: 8,
@ -748,10 +749,9 @@ describe("misc", () => {
},
},
{ memcmp: { offset: 40, bytes: filterable1.toBase58() } },
]
);
const allAccountsFilteredByProgramFilters2 = await program.account.dataWithFilter.all(
[
]);
const allAccountsFilteredByProgramFilters2 =
await program.account.dataWithFilter.all([
{
memcmp: {
offset: 8,
@ -759,8 +759,7 @@ describe("misc", () => {
},
},
{ memcmp: { offset: 40, bytes: filterable2.toBase58() } },
]
);
]);
// Without filters there should be 4 accounts.
assert.equal(allAccounts.length, 4);
// Filtering by main wallet there should be 3 accounts.
@ -861,14 +860,17 @@ describe("misc", () => {
});
it("init_if_needed throws if account exists but is not owned by the expected program", async () => {
const newAcc = await anchor.web3.PublicKey.findProgramAddress([utf8.encode("hello")], program.programId);
const newAcc = await anchor.web3.PublicKey.findProgramAddress(
[utf8.encode("hello")],
program.programId
);
await program.rpc.testInitIfNeededChecksOwner({
accounts: {
data: newAcc[0],
systemProgram: anchor.web3.SystemProgram.programId,
payer: program.provider.wallet.publicKey,
owner: program.programId
}
owner: program.programId,
},
});
try {
@ -877,7 +879,7 @@ describe("misc", () => {
data: newAcc[0],
systemProgram: anchor.web3.SystemProgram.programId,
payer: program.provider.wallet.publicKey,
owner: anchor.web3.Keypair.generate().publicKey
owner: anchor.web3.Keypair.generate().publicKey,
},
});
assert.ok(false);
@ -887,20 +889,26 @@ describe("misc", () => {
});
it("init_if_needed throws if pda account exists but does not have the expected seeds", async () => {
const newAcc = await anchor.web3.PublicKey.findProgramAddress([utf8.encode("nothello")], program.programId);
const newAcc = await anchor.web3.PublicKey.findProgramAddress(
[utf8.encode("nothello")],
program.programId
);
await program.rpc.testInitIfNeededChecksSeeds("nothello", {
accounts: {
data: newAcc[0],
systemProgram: anchor.web3.SystemProgram.programId,
payer: program.provider.wallet.publicKey,
}
},
});
// this will throw if it is not a proper PDA
// we need this so we know that the following tx failed
// not because it couldn't create this pda
// but because the two pdas were different
anchor.web3.PublicKey.createProgramAddress([utf8.encode("hello")], program.programId);
anchor.web3.PublicKey.createProgramAddress(
[utf8.encode("hello")],
program.programId
);
try {
await program.rpc.testInitIfNeededChecksSeeds("hello", {
@ -908,7 +916,7 @@ describe("misc", () => {
data: newAcc[0],
systemProgram: anchor.web3.SystemProgram.programId,
payer: program.provider.wallet.publicKey,
owner: anchor.web3.Keypair.generate().publicKey
owner: anchor.web3.Keypair.generate().publicKey,
},
});
assert.ok(false);
@ -917,8 +925,6 @@ describe("misc", () => {
}
});
it("init_if_needed throws if account exists but is not the expected space", async () => {
const newAcc = anchor.web3.Keypair.generate();
await program.rpc.initWithSpace(3, {
@ -959,7 +965,7 @@ describe("misc", () => {
});
try {
await program.rpc.testInitMintIfNeeded(6,{
await program.rpc.testInitMintIfNeeded(6, {
accounts: {
mint: mint.publicKey,
payer: program.provider.wallet.publicKey,
@ -967,7 +973,7 @@ describe("misc", () => {
tokenProgram: TOKEN_PROGRAM_ID,
rent: anchor.web3.SYSVAR_RENT_PUBKEY,
mintAuthority: anchor.web3.Keypair.generate().publicKey,
freezeAuthority: program.provider.wallet.publicKey
freezeAuthority: program.provider.wallet.publicKey,
},
signers: [mint],
});
@ -991,7 +997,7 @@ describe("misc", () => {
});
try {
await program.rpc.testInitMintIfNeeded(6,{
await program.rpc.testInitMintIfNeeded(6, {
accounts: {
mint: mint.publicKey,
payer: program.provider.wallet.publicKey,
@ -999,7 +1005,7 @@ describe("misc", () => {
tokenProgram: TOKEN_PROGRAM_ID,
rent: anchor.web3.SYSVAR_RENT_PUBKEY,
mintAuthority: program.provider.wallet.publicKey,
freezeAuthority: anchor.web3.Keypair.generate().publicKey
freezeAuthority: anchor.web3.Keypair.generate().publicKey,
},
signers: [mint],
});
@ -1023,7 +1029,7 @@ describe("misc", () => {
});
try {
await program.rpc.testInitMintIfNeeded(9,{
await program.rpc.testInitMintIfNeeded(9, {
accounts: {
mint: mint.publicKey,
payer: program.provider.wallet.publicKey,
@ -1031,7 +1037,7 @@ describe("misc", () => {
tokenProgram: TOKEN_PROGRAM_ID,
rent: anchor.web3.SYSVAR_RENT_PUBKEY,
mintAuthority: program.provider.wallet.publicKey,
freezeAuthority: program.provider.wallet.publicKey
freezeAuthority: program.provider.wallet.publicKey,
},
signers: [mint],
});
@ -1185,14 +1191,14 @@ describe("misc", () => {
systemProgram: anchor.web3.SystemProgram.programId,
tokenProgram: TOKEN_PROGRAM_ID,
associatedTokenProgram: ASSOCIATED_TOKEN_PROGRAM_ID,
authority: anchor.web3.Keypair.generate().publicKey
authority: anchor.web3.Keypair.generate().publicKey,
},
});
assert.ok(false);
} catch (err) {
assert.equal(err.code, 2015);
}
})
});
it("init_if_needed throws if associated token exists but has the wrong mint", async () => {
const mint = anchor.web3.Keypair.generate();
@ -1248,14 +1254,14 @@ describe("misc", () => {
systemProgram: anchor.web3.SystemProgram.programId,
tokenProgram: TOKEN_PROGRAM_ID,
associatedTokenProgram: ASSOCIATED_TOKEN_PROGRAM_ID,
authority: program.provider.wallet.publicKey
authority: program.provider.wallet.publicKey,
},
});
assert.ok(false);
} catch (err) {
assert.equal(err.code, 2014);
}
})
});
it("Can use multidimensional array", async () => {
const array2d = new Array(10).fill(new Array(10).fill(99));

View File

@ -1,4 +1,3 @@
// Migrations are an early feature. Currently, they're nothing more than this
// single deploy script that's invoked from the CLI, injecting a provider
// configured from the workspace's Anchor.toml.
@ -10,4 +9,4 @@ module.exports = async function (provider) {
anchor.setProvider(provider);
// Add your deploy script here.
}
};

View File

@ -9,13 +9,11 @@ describe("multisig", () => {
it("Tests the multisig program", async () => {
const multisig = anchor.web3.Keypair.generate();
const [
multisigSigner,
nonce,
] = await anchor.web3.PublicKey.findProgramAddress(
[multisig.publicKey.toBuffer()],
program.programId
);
const [multisigSigner, nonce] =
await anchor.web3.PublicKey.findProgramAddress(
[multisig.publicKey.toBuffer()],
program.programId
);
const multisigSize = 200; // Big enough.
const ownerA = anchor.web3.Keypair.generate();
@ -39,7 +37,9 @@ describe("multisig", () => {
signers: [multisig],
});
let multisigAccount = await program.account.multisig.fetch(multisig.publicKey);
let multisigAccount = await program.account.multisig.fetch(
multisig.publicKey
);
assert.equal(multisigAccount.nonce, nonce);
assert.ok(multisigAccount.threshold.eq(new anchor.BN(2)));
@ -59,8 +59,8 @@ describe("multisig", () => {
},
];
const newOwners = [ownerA.publicKey, ownerB.publicKey, ownerD.publicKey];
const data = program.coder.instruction.encode('set_owners', {
owners: newOwners,
const data = program.coder.instruction.encode("set_owners", {
owners: newOwners,
});
const transaction = anchor.web3.Keypair.generate();
@ -81,7 +81,9 @@ describe("multisig", () => {
signers: [transaction, ownerA],
});
const txAccount = await program.account.transaction.fetch(transaction.publicKey);
const txAccount = await program.account.transaction.fetch(
transaction.publicKey
);
assert.ok(txAccount.programId.equals(pid));
assert.deepEqual(txAccount.accounts, accounts);

View File

@ -1,6 +1,10 @@
{
"name": "anchor-tests",
"private": true,
"scripts": {
"lint:fix": "prettier */*.js \"*/**/*{.js,.ts}\" -w",
"lint": "prettier */*.js \"*/**/*{.js,.ts}\" --check"
},
"workspaces": [
"cashiers-check",
"cfo",
@ -35,6 +39,7 @@
"chai": "^4.3.4",
"mocha": "^9.1.3",
"ts-mocha": "^8.0.0",
"typescript": "^4.4.4"
"typescript": "^4.4.4",
"prettier": "^2.5.1"
}
}

View File

@ -1,21 +1,22 @@
import { Buffer } from 'buffer'
import { BN, Program, web3 } from '@project-serum/anchor'
import { Buffer } from "buffer";
import { BN, Program, web3 } from "@project-serum/anchor";
export const Magic = 0xa1b2c3d4
export const Version1 = 1
export const Version = Version1
export const PriceStatus = ['Unknown', 'Trading', 'Halted', 'Auction']
export const CorpAction = ['NoCorpAct']
export const PriceType = ['Unknown', 'Price', 'TWAP', 'Volatility']
export const Magic = 0xa1b2c3d4;
export const Version1 = 1;
export const Version = Version1;
export const PriceStatus = ["Unknown", "Trading", "Halted", "Auction"];
export const CorpAction = ["NoCorpAct"];
export const PriceType = ["Unknown", "Price", "TWAP", "Volatility"];
const empty32Buffer = Buffer.alloc(32)
const PKorNull = (data: Buffer) => (data.equals(empty32Buffer) ? null : new web3.PublicKey(data))
const empty32Buffer = Buffer.alloc(32);
const PKorNull = (data: Buffer) =>
data.equals(empty32Buffer) ? null : new web3.PublicKey(data);
interface ICreatePriceFeed {
oracleProgram: Program
initPrice: number
confidence?: BN
expo?: number
oracleProgram: Program;
initPrice: number;
confidence?: BN;
expo?: number;
}
export const createPriceFeed = async ({
oracleProgram,
@ -23,160 +24,200 @@ export const createPriceFeed = async ({
confidence,
expo = -4,
}: ICreatePriceFeed) => {
const conf = confidence || new BN((initPrice / 10) * 10 ** -expo)
const collateralTokenFeed = new web3.Account()
await oracleProgram.rpc.initialize(new BN(initPrice * 10 ** -expo), expo, conf, {
accounts: { price: collateralTokenFeed.publicKey },
signers: [collateralTokenFeed],
instructions: [
web3.SystemProgram.createAccount({
fromPubkey: oracleProgram.provider.wallet.publicKey,
newAccountPubkey: collateralTokenFeed.publicKey,
space: 3312,
lamports: await oracleProgram.provider.connection.getMinimumBalanceForRentExemption(3312),
programId: oracleProgram.programId,
}),
],
})
return collateralTokenFeed.publicKey
}
const conf = confidence || new BN((initPrice / 10) * 10 ** -expo);
const collateralTokenFeed = new web3.Account();
await oracleProgram.rpc.initialize(
new BN(initPrice * 10 ** -expo),
expo,
conf,
{
accounts: { price: collateralTokenFeed.publicKey },
signers: [collateralTokenFeed],
instructions: [
web3.SystemProgram.createAccount({
fromPubkey: oracleProgram.provider.wallet.publicKey,
newAccountPubkey: collateralTokenFeed.publicKey,
space: 3312,
lamports:
await oracleProgram.provider.connection.getMinimumBalanceForRentExemption(
3312
),
programId: oracleProgram.programId,
}),
],
}
);
return collateralTokenFeed.publicKey;
};
export const setFeedPrice = async (
oracleProgram: Program,
newPrice: number,
priceFeed: web3.PublicKey
) => {
const info = await oracleProgram.provider.connection.getAccountInfo(priceFeed)
const data = parsePriceData(info.data)
const info = await oracleProgram.provider.connection.getAccountInfo(
priceFeed
);
const data = parsePriceData(info.data);
await oracleProgram.rpc.setPrice(new BN(newPrice * 10 ** -data.exponent), {
accounts: { price: priceFeed },
})
}
export const getFeedData = async (oracleProgram: Program, priceFeed: web3.PublicKey) => {
const info = await oracleProgram.provider.connection.getAccountInfo(priceFeed)
return parsePriceData(info.data)
}
});
};
export const getFeedData = async (
oracleProgram: Program,
priceFeed: web3.PublicKey
) => {
const info = await oracleProgram.provider.connection.getAccountInfo(
priceFeed
);
return parsePriceData(info.data);
};
// https://github.com/nodejs/node/blob/v14.17.0/lib/internal/errors.js#L758
const ERR_BUFFER_OUT_OF_BOUNDS = () => new Error('Attempt to access memory outside buffer bounds')
const ERR_BUFFER_OUT_OF_BOUNDS = () =>
new Error("Attempt to access memory outside buffer bounds");
// https://github.com/nodejs/node/blob/v14.17.0/lib/internal/errors.js#L968
const ERR_INVALID_ARG_TYPE = (name: string, expected: string, actual: any) =>
new Error(`The "${name}" argument must be of type ${expected}. Received ${actual}`)
new Error(
`The "${name}" argument must be of type ${expected}. Received ${actual}`
);
// https://github.com/nodejs/node/blob/v14.17.0/lib/internal/errors.js#L1262
const ERR_OUT_OF_RANGE = (str: string, range: string, received: number) =>
new Error(`The value of "${str} is out of range. It must be ${range}. Received ${received}`)
new Error(
`The value of "${str} is out of range. It must be ${range}. Received ${received}`
);
// https://github.com/nodejs/node/blob/v14.17.0/lib/internal/validators.js#L127-L130
function validateNumber(value: any, name: string) {
if (typeof value !== 'number') throw ERR_INVALID_ARG_TYPE(name, 'number', value)
if (typeof value !== "number")
throw ERR_INVALID_ARG_TYPE(name, "number", value);
}
// https://github.com/nodejs/node/blob/v14.17.0/lib/internal/buffer.js#L68-L80
function boundsError(value: number, length: number) {
if (Math.floor(value) !== value) {
validateNumber(value, 'offset')
throw ERR_OUT_OF_RANGE('offset', 'an integer', value)
validateNumber(value, "offset");
throw ERR_OUT_OF_RANGE("offset", "an integer", value);
}
if (length < 0) throw ERR_BUFFER_OUT_OF_BOUNDS()
if (length < 0) throw ERR_BUFFER_OUT_OF_BOUNDS();
throw ERR_OUT_OF_RANGE('offset', `>= 0 and <= ${length}`, value)
throw ERR_OUT_OF_RANGE("offset", `>= 0 and <= ${length}`, value);
}
export function readBigInt64LE(buffer: Buffer, offset = 0): bigint {
validateNumber(offset, 'offset')
const first = buffer[offset]
const last = buffer[offset + 7]
if (first === undefined || last === undefined) boundsError(offset, buffer.length - 8)
validateNumber(offset, "offset");
const first = buffer[offset];
const last = buffer[offset + 7];
if (first === undefined || last === undefined)
boundsError(offset, buffer.length - 8);
const val =
buffer[offset + 4] + buffer[offset + 5] * 2 ** 8 + buffer[offset + 6] * 2 ** 16 + (last << 24) // Overflow
buffer[offset + 4] +
buffer[offset + 5] * 2 ** 8 +
buffer[offset + 6] * 2 ** 16 +
(last << 24); // Overflow
return (
(BigInt(val) << BigInt(32)) +
BigInt(
first + buffer[++offset] * 2 ** 8 + buffer[++offset] * 2 ** 16 + buffer[++offset] * 2 ** 24
first +
buffer[++offset] * 2 ** 8 +
buffer[++offset] * 2 ** 16 +
buffer[++offset] * 2 ** 24
)
)
);
}
// https://github.com/nodejs/node/blob/v14.17.0/lib/internal/buffer.js#L89-L107
export function readBigUInt64LE(buffer: Buffer, offset = 0): bigint {
validateNumber(offset, 'offset')
const first = buffer[offset]
const last = buffer[offset + 7]
if (first === undefined || last === undefined) boundsError(offset, buffer.length - 8)
validateNumber(offset, "offset");
const first = buffer[offset];
const last = buffer[offset + 7];
if (first === undefined || last === undefined)
boundsError(offset, buffer.length - 8);
const lo =
first + buffer[++offset] * 2 ** 8 + buffer[++offset] * 2 ** 16 + buffer[++offset] * 2 ** 24
first +
buffer[++offset] * 2 ** 8 +
buffer[++offset] * 2 ** 16 +
buffer[++offset] * 2 ** 24;
const hi =
buffer[++offset] + buffer[++offset] * 2 ** 8 + buffer[++offset] * 2 ** 16 + last * 2 ** 24
buffer[++offset] +
buffer[++offset] * 2 ** 8 +
buffer[++offset] * 2 ** 16 +
last * 2 ** 24;
return BigInt(lo) + (BigInt(hi) << BigInt(32)) // tslint:disable-line:no-bitwise
return BigInt(lo) + (BigInt(hi) << BigInt(32)); // tslint:disable-line:no-bitwise
}
export const parsePriceData = (data: Buffer) => {
// Pyth magic number.
const magic = data.readUInt32LE(0)
const magic = data.readUInt32LE(0);
// Program version.
const version = data.readUInt32LE(4)
const version = data.readUInt32LE(4);
// Account type.
const type = data.readUInt32LE(8)
const type = data.readUInt32LE(8);
// Price account size.
const size = data.readUInt32LE(12)
const size = data.readUInt32LE(12);
// Price or calculation type.
const priceType = data.readUInt32LE(16)
const priceType = data.readUInt32LE(16);
// Price exponent.
const exponent = data.readInt32LE(20)
const exponent = data.readInt32LE(20);
// Number of component prices.
const numComponentPrices = data.readUInt32LE(24)
const numComponentPrices = data.readUInt32LE(24);
// unused
// const unused = accountInfo.data.readUInt32LE(28)
// Currently accumulating price slot.
const currentSlot = readBigUInt64LE(data, 32)
const currentSlot = readBigUInt64LE(data, 32);
// Valid on-chain slot of aggregate price.
const validSlot = readBigUInt64LE(data, 40)
const validSlot = readBigUInt64LE(data, 40);
// Time-weighted average price.
const twapComponent = readBigInt64LE(data, 48)
const twap = Number(twapComponent) * 10 ** exponent
const twapComponent = readBigInt64LE(data, 48);
const twap = Number(twapComponent) * 10 ** exponent;
// Annualized price volatility.
const avolComponent = readBigUInt64LE(data, 56)
const avol = Number(avolComponent) * 10 ** exponent
const avolComponent = readBigUInt64LE(data, 56);
const avol = Number(avolComponent) * 10 ** exponent;
// Space for future derived values.
const drv0Component = readBigInt64LE(data, 64)
const drv0 = Number(drv0Component) * 10 ** exponent
const drv1Component = readBigInt64LE(data, 72)
const drv1 = Number(drv1Component) * 10 ** exponent
const drv2Component = readBigInt64LE(data, 80)
const drv2 = Number(drv2Component) * 10 ** exponent
const drv3Component = readBigInt64LE(data, 88)
const drv3 = Number(drv3Component) * 10 ** exponent
const drv4Component = readBigInt64LE(data, 96)
const drv4 = Number(drv4Component) * 10 ** exponent
const drv5Component = readBigInt64LE(data, 104)
const drv5 = Number(drv5Component) * 10 ** exponent
const drv0Component = readBigInt64LE(data, 64);
const drv0 = Number(drv0Component) * 10 ** exponent;
const drv1Component = readBigInt64LE(data, 72);
const drv1 = Number(drv1Component) * 10 ** exponent;
const drv2Component = readBigInt64LE(data, 80);
const drv2 = Number(drv2Component) * 10 ** exponent;
const drv3Component = readBigInt64LE(data, 88);
const drv3 = Number(drv3Component) * 10 ** exponent;
const drv4Component = readBigInt64LE(data, 96);
const drv4 = Number(drv4Component) * 10 ** exponent;
const drv5Component = readBigInt64LE(data, 104);
const drv5 = Number(drv5Component) * 10 ** exponent;
// Product id / reference account.
const productAccountKey = new web3.PublicKey(data.slice(112, 144))
const productAccountKey = new web3.PublicKey(data.slice(112, 144));
// Next price account in list.
const nextPriceAccountKey = PKorNull(data.slice(144, 176))
const nextPriceAccountKey = PKorNull(data.slice(144, 176));
// Aggregate price updater.
const aggregatePriceUpdaterAccountKey = new web3.PublicKey(data.slice(176, 208))
const aggregatePriceInfo = parsePriceInfo(data.slice(208, 240), exponent)
const aggregatePriceUpdaterAccountKey = new web3.PublicKey(
data.slice(176, 208)
);
const aggregatePriceInfo = parsePriceInfo(data.slice(208, 240), exponent);
// Price components - up to 32.
const priceComponents = []
let offset = 240
let shouldContinue = true
const priceComponents = [];
let offset = 240;
let shouldContinue = true;
while (offset < data.length && shouldContinue) {
const publisher = PKorNull(data.slice(offset, offset + 32))
offset += 32
const publisher = PKorNull(data.slice(offset, offset + 32));
offset += 32;
if (publisher) {
const aggregate = parsePriceInfo(data.slice(offset, offset + 32), exponent)
offset += 32
const latest = parsePriceInfo(data.slice(offset, offset + 32), exponent)
offset += 32
priceComponents.push({ publisher, aggregate, latest })
const aggregate = parsePriceInfo(
data.slice(offset, offset + 32),
exponent
);
offset += 32;
const latest = parsePriceInfo(data.slice(offset, offset + 32), exponent);
offset += 32;
priceComponents.push({ publisher, aggregate, latest });
} else {
shouldContinue = false
shouldContinue = false;
}
}
return {
@ -210,56 +251,56 @@ export const parsePriceData = (data: Buffer) => {
aggregatePriceUpdaterAccountKey,
...aggregatePriceInfo,
priceComponents,
}
}
};
};
interface ProductAttributes {
[index: string]: string
[index: string]: string;
}
export const parseProductData = (data: Buffer) => {
// Pyth magic number.
const magic = data.readUInt32LE(0)
const magic = data.readUInt32LE(0);
// Program version.
const version = data.readUInt32LE(4)
const version = data.readUInt32LE(4);
// Account type.
const type = data.readUInt32LE(8)
const type = data.readUInt32LE(8);
// Price account size.
const size = data.readUInt32LE(12)
const size = data.readUInt32LE(12);
// First price account in list.
const priceAccountBytes = data.slice(16, 48)
const priceAccountKey = new web3.PublicKey(priceAccountBytes)
const product: ProductAttributes = {}
let idx = 48
const priceAccountBytes = data.slice(16, 48);
const priceAccountKey = new web3.PublicKey(priceAccountBytes);
const product: ProductAttributes = {};
let idx = 48;
while (idx < data.length) {
const keyLength = data[idx]
idx++
const keyLength = data[idx];
idx++;
if (keyLength) {
const key = data.slice(idx, idx + keyLength).toString()
idx += keyLength
const valueLength = data[idx]
idx++
const value = data.slice(idx, idx + valueLength).toString()
idx += valueLength
product[key] = value
const key = data.slice(idx, idx + keyLength).toString();
idx += keyLength;
const valueLength = data[idx];
idx++;
const value = data.slice(idx, idx + valueLength).toString();
idx += valueLength;
product[key] = value;
}
}
return { magic, version, type, size, priceAccountKey, product }
}
return { magic, version, type, size, priceAccountKey, product };
};
const parsePriceInfo = (data: Buffer, exponent: number) => {
// Aggregate price.
const priceComponent = data.readBigUInt64LE(0)
const price = Number(priceComponent) * 10 ** exponent
const priceComponent = data.readBigUInt64LE(0);
const price = Number(priceComponent) * 10 ** exponent;
// Aggregate confidence.
const confidenceComponent = data.readBigUInt64LE(8)
const confidence = Number(confidenceComponent) * 10 ** exponent
const confidenceComponent = data.readBigUInt64LE(8);
const confidence = Number(confidenceComponent) * 10 ** exponent;
// Aggregate status.
const status = data.readUInt32LE(16)
const status = data.readUInt32LE(16);
// Aggregate corporate action.
const corporateAction = data.readUInt32LE(20)
const corporateAction = data.readUInt32LE(20);
// Aggregate publish slot.
const publishSlot = data.readBigUInt64LE(24)
const publishSlot = data.readBigUInt64LE(24);
return {
priceComponent,
price,
@ -268,5 +309,5 @@ const parsePriceInfo = (data: Buffer, exponent: number) => {
status,
corporateAction,
publishSlot,
}
}
};
};

View File

@ -1,39 +1,39 @@
import * as anchor from '@project-serum/anchor'
import { BN, Program, web3 } from '@project-serum/anchor'
import assert from 'assert'
import { createPriceFeed, setFeedPrice, getFeedData } from './oracleUtils'
import * as anchor from "@project-serum/anchor";
import { BN, Program, web3 } from "@project-serum/anchor";
import assert from "assert";
import { createPriceFeed, setFeedPrice, getFeedData } from "./oracleUtils";
describe('pyth-oracle', () => {
anchor.setProvider(anchor.Provider.env())
const program = anchor.workspace.Pyth as Program
describe("pyth-oracle", () => {
anchor.setProvider(anchor.Provider.env());
const program = anchor.workspace.Pyth as Program;
it('initialize', async () => {
const price = 50000
it("initialize", async () => {
const price = 50000;
const priceFeedAddress = await createPriceFeed({
oracleProgram: program,
initPrice: price,
expo: -6,
})
const feedData = await getFeedData(program, priceFeedAddress)
assert.ok(feedData.price === price)
})
});
const feedData = await getFeedData(program, priceFeedAddress);
assert.ok(feedData.price === price);
});
it('change feed price', async () => {
const price = 50000
const expo = -7
it("change feed price", async () => {
const price = 50000;
const expo = -7;
const priceFeedAddress = await createPriceFeed({
oracleProgram: program,
initPrice: price,
expo: expo,
})
const feedDataBefore = await getFeedData(program, priceFeedAddress)
assert.ok(feedDataBefore.price === price)
assert.ok(feedDataBefore.exponent === expo)
});
const feedDataBefore = await getFeedData(program, priceFeedAddress);
assert.ok(feedDataBefore.price === price);
assert.ok(feedDataBefore.exponent === expo);
const newPrice = 55000
await setFeedPrice(program, newPrice, priceFeedAddress)
const feedDataAfter = await getFeedData(program, priceFeedAddress)
assert.ok(feedDataAfter.price === newPrice)
assert.ok(feedDataAfter.exponent === expo)
})
})
const newPrice = 55000;
await setFeedPrice(program, newPrice, priceFeedAddress);
const feedDataAfter = await getFeedData(program, priceFeedAddress);
assert.ok(feedDataAfter.price === newPrice);
assert.ok(feedDataAfter.exponent === expo);
});
});

View File

@ -9,4 +9,4 @@ module.exports = async function (provider) {
anchor.setProvider(provider);
// Add your deploy script here.
}
};

View File

@ -277,43 +277,39 @@ async function setupMarket({
);
for (let k = 0; k < asks.length; k += 1) {
let ask = asks[k];
const {
transaction,
signers,
} = await MARKET_A_USDC.makePlaceOrderTransaction(provider.connection, {
owner: marketMaker.account,
payer: marketMaker.baseToken,
side: "sell",
price: ask[0],
size: ask[1],
orderType: "postOnly",
clientId: undefined,
openOrdersAddressKey: undefined,
openOrdersAccount: undefined,
feeDiscountPubkey: null,
selfTradeBehavior: "abortTransaction",
});
const { transaction, signers } =
await MARKET_A_USDC.makePlaceOrderTransaction(provider.connection, {
owner: marketMaker.account,
payer: marketMaker.baseToken,
side: "sell",
price: ask[0],
size: ask[1],
orderType: "postOnly",
clientId: undefined,
openOrdersAddressKey: undefined,
openOrdersAccount: undefined,
feeDiscountPubkey: null,
selfTradeBehavior: "abortTransaction",
});
await provider.send(transaction, signers.concat(marketMaker.account));
}
for (let k = 0; k < bids.length; k += 1) {
let bid = bids[k];
const {
transaction,
signers,
} = await MARKET_A_USDC.makePlaceOrderTransaction(provider.connection, {
owner: marketMaker.account,
payer: marketMaker.quoteToken,
side: "buy",
price: bid[0],
size: bid[1],
orderType: "postOnly",
clientId: undefined,
openOrdersAddressKey: undefined,
openOrdersAccount: undefined,
feeDiscountPubkey: null,
selfTradeBehavior: "abortTransaction",
});
const { transaction, signers } =
await MARKET_A_USDC.makePlaceOrderTransaction(provider.connection, {
owner: marketMaker.account,
payer: marketMaker.quoteToken,
side: "buy",
price: bid[0],
size: bid[1],
orderType: "postOnly",
clientId: undefined,
openOrdersAddressKey: undefined,
openOrdersAccount: undefined,
feeDiscountPubkey: null,
selfTradeBehavior: "abortTransaction",
});
await provider.send(transaction, signers.concat(marketMaker.account));
}

View File

@ -1,33 +1,33 @@
const anchor = require('@project-serum/anchor');
const splToken = require('@solana/spl-token');
const assert = require('assert');
const anchor = require("@project-serum/anchor");
const splToken = require("@solana/spl-token");
const assert = require("assert");
describe('system_accounts', () => {
describe("system_accounts", () => {
anchor.setProvider(anchor.Provider.local());
const program = anchor.workspace.SystemAccounts;
const authority = program.provider.wallet.payer;
const wallet = anchor.web3.Keypair.generate();
it('Is initialized!', async () => {
it("Is initialized!", async () => {
const tx = await program.rpc.initialize({
accounts: {
authority: authority.publicKey,
wallet: wallet.publicKey
wallet: wallet.publicKey,
},
signers: [authority]
signers: [authority],
});
console.log("Your transaction signature", tx);
});
it('Emits an AccountNotSystemOwned error', async () => {
it("Emits an AccountNotSystemOwned error", async () => {
const mint = await splToken.Token.createMint(
program.provider.connection,
authority,
authority.publicKey,
null,
9,
splToken.TOKEN_PROGRAM_ID,
splToken.TOKEN_PROGRAM_ID
);
const tokenAccount = await mint.createAssociatedTokenAccount(
@ -38,20 +38,20 @@ describe('system_accounts', () => {
tokenAccount,
authority.publicKey,
[],
1 * anchor.web3.LAMPORTS_PER_SOL,
1 * anchor.web3.LAMPORTS_PER_SOL
);
try {
await program.rpc.initialize({
accounts: {
authority: authority.publicKey,
wallet: tokenAccount
wallet: tokenAccount,
},
signers: [authority]
})
signers: [authority],
});
assert.ok(false);
} catch (err) {
const errMsg = 'The given account is not owned by the system program';
const errMsg = "The given account is not owned by the system program";
assert.equal(err.toString(), errMsg);
assert.equal(err.msg, errMsg);
assert.equal(err.code, 3011);

View File

@ -1,11 +1,10 @@
const anchor = require('@project-serum/anchor');
describe('sysvars', () => {
const anchor = require("@project-serum/anchor");
describe("sysvars", () => {
// Configure the client to use the local cluster.
anchor.setProvider(anchor.Provider.local());
it('Is initialized!', async () => {
it("Is initialized!", async () => {
const program = anchor.workspace.Sysvars;
const tx = await program.rpc.sysvars({
accounts: {

View File

@ -9,4 +9,4 @@ module.exports = async function (provider) {
anchor.setProvider(provider);
// Add your deploy script here.
}
};

View File

@ -1,14 +1,13 @@
const anchor = require('@project-serum/anchor');
describe('tictactoe', () => {
const anchor = require("@project-serum/anchor");
describe("tictactoe", () => {
anchor.setProvider(anchor.Provider.env());
const program = anchor.workspace.Tictactoe;
let dashboard = anchor.web3.Keypair.generate()
let game = anchor.web3.Keypair.generate()
let player_o = anchor.web3.Keypair.generate()
let dashboard = anchor.web3.Keypair.generate();
let game = anchor.web3.Keypair.generate();
let player_o = anchor.web3.Keypair.generate();
it('Initialize Dashboard', async () => {
it("Initialize Dashboard", async () => {
const tx = await program.rpc.initializeDashboard({
accounts: {
authority: program.provider.wallet.publicKey,
@ -16,13 +15,15 @@ describe('tictactoe', () => {
rent: anchor.web3.SYSVAR_RENT_PUBKEY,
},
signers: [dashboard],
instructions: [await program.account.dashboard.createInstruction(dashboard)]
})
instructions: [
await program.account.dashboard.createInstruction(dashboard),
],
});
console.log("transaction: ", tx)
console.log("transaction: ", tx);
});
it('Initialize Game', async () => {
it("Initialize Game", async () => {
const tx = await program.rpc.initialize({
accounts: {
playerX: program.provider.wallet.publicKey,
@ -31,127 +32,126 @@ describe('tictactoe', () => {
rent: anchor.web3.SYSVAR_RENT_PUBKEY,
},
signers: [game],
instructions: [await program.account.game.createInstruction(game)]
})
instructions: [await program.account.game.createInstruction(game)],
});
console.log("transaction: ", tx)
console.log("transaction: ", tx);
});
it('Player O joins', async () => {
it("Player O joins", async () => {
const tx = await program.rpc.playerJoin({
accounts: {
playerO: player_o.publicKey,
game: game.publicKey,
},
signers: [player_o],
})
});
console.log("transaction: ", tx)
console.log("transaction: ", tx);
});
it('Player x plays', async () => {
it("Player x plays", async () => {
const tx = await program.rpc.playerMove(1, 0, {
accounts: {
player: program.provider.wallet.publicKey,
game: game.publicKey,
},
})
console.log("transaction: ", tx)
});
console.log("transaction: ", tx);
});
it('Player o plays', async () => {
it("Player o plays", async () => {
const tx = await program.rpc.playerMove(2, 1, {
accounts: {
player: player_o.publicKey,
game: game.publicKey,
},
signers: [player_o]
})
console.log("transaction: ", tx)
signers: [player_o],
});
console.log("transaction: ", tx);
});
it('Player x plays', async () => {
it("Player x plays", async () => {
const tx = await program.rpc.playerMove(1, 3, {
accounts: {
player: program.provider.wallet.publicKey,
game: game.publicKey,
},
})
console.log("transaction: ", tx)
});
console.log("transaction: ", tx);
});
it('Player o plays', async () => {
it("Player o plays", async () => {
const tx = await program.rpc.playerMove(2, 6, {
accounts: {
player: player_o.publicKey,
game: game.publicKey,
},
signers: [player_o]
})
console.log("transaction: ", tx)
signers: [player_o],
});
console.log("transaction: ", tx);
});
it('Player x plays', async () => {
it("Player x plays", async () => {
const tx = await program.rpc.playerMove(1, 2, {
accounts: {
player: program.provider.wallet.publicKey,
game: game.publicKey,
},
})
console.log("transaction: ", tx)
});
console.log("transaction: ", tx);
});
it('Player o plays', async () => {
it("Player o plays", async () => {
const tx = await program.rpc.playerMove(2, 4, {
accounts: {
player: player_o.publicKey,
game: game.publicKey,
},
signers: [player_o]
})
console.log("transaction: ", tx)
signers: [player_o],
});
console.log("transaction: ", tx);
});
it('Player x plays', async () => {
it("Player x plays", async () => {
const tx = await program.rpc.playerMove(1, 5, {
accounts: {
player: program.provider.wallet.publicKey,
game: game.publicKey,
},
})
console.log("transaction: ", tx)
});
console.log("transaction: ", tx);
});
it('Player o plays', async () => {
it("Player o plays", async () => {
const tx = await program.rpc.playerMove(2, 8, {
accounts: {
player: player_o.publicKey,
game: game.publicKey,
},
signers: [player_o]
})
console.log("transaction: ", tx)
signers: [player_o],
});
console.log("transaction: ", tx);
});
it('Player x plays', async () => {
it("Player x plays", async () => {
const tx = await program.rpc.playerMove(1, 7, {
accounts: {
player: program.provider.wallet.publicKey,
game: game.publicKey,
},
})
console.log("transaction: ", tx)
});
console.log("transaction: ", tx);
});
it('Status', async () => {
it("Status", async () => {
const tx = await program.rpc.status({
accounts: {
dashboard: dashboard.publicKey,
game: game.publicKey,
},
})
});
console.log("transaction: ", tx)
console.log("transaction: ", tx);
});
});

View File

@ -19,4 +19,4 @@ module.exports = async function (provider) {
}
await deployAsync("Typescript migration example complete.");
}
};

View File

@ -1,11 +1,10 @@
import * as anchor from '@project-serum/anchor';
describe('typescript', () => {
import * as anchor from "@project-serum/anchor";
describe("typescript", () => {
// Configure the client to use the local cluster.
anchor.setProvider(anchor.Provider.env());
it('Is initialized!', async () => {
it("Is initialized!", async () => {
// Add your test here.
const program = anchor.workspace.Typescript;
const tx = await program.rpc.initialize();

View File

@ -962,6 +962,11 @@ picomatch@^2.0.4, picomatch@^2.2.1:
resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-2.3.0.tgz#f1f061de8f6a4bf022892e2d128234fb98302972"
integrity sha512-lY1Q/PiJGC2zOv/z391WOTD+Z02bCgsFfvxoXXf6h7kv9o+WmsmzYqrAwY63sNgOxE4xEdq0WyUnXfKeBrSvYw==
prettier@^2.5.1:
version "2.5.1"
resolved "https://registry.yarnpkg.com/prettier/-/prettier-2.5.1.tgz#fff75fa9d519c54cf0fce328c1017d94546bc56a"
integrity sha512-vBZcPRUR5MZJwoyi3ZoyQlc1rXeEck8KgeC9AwwOn+exuxLxq5toTRDTSaVrXHxelDMHy9zlicw8u66yxoSUFg==
randombytes@^2.1.0:
version "2.1.0"
resolved "https://registry.yarnpkg.com/randombytes/-/randombytes-2.1.0.tgz#df6f84372f0270dc65cdf6291349ab7a473d4f2a"

View File

@ -9,4 +9,4 @@ module.exports = async function (provider) {
anchor.setProvider(provider);
// Add your deploy script here.
}
};

View File

@ -1,17 +1,17 @@
const anchor = require('@project-serum/anchor')
const PublicKey = anchor.web3.PublicKey
const BN = anchor.BN
const assert = require('assert')
const anchor = require("@project-serum/anchor");
const PublicKey = anchor.web3.PublicKey;
const BN = anchor.BN;
const assert = require("assert");
describe('zero-copy', () => {
describe("zero-copy", () => {
// Configure the client to use the local cluster.
anchor.setProvider(anchor.Provider.env())
anchor.setProvider(anchor.Provider.env());
const program = anchor.workspace.ZeroCopy
const programCpi = anchor.workspace.ZeroCpi
const program = anchor.workspace.ZeroCopy;
const programCpi = anchor.workspace.ZeroCpi;
const foo = anchor.web3.Keypair.generate()
it('Is creates a zero copy account', async () => {
const foo = anchor.web3.Keypair.generate();
it("Is creates a zero copy account", async () => {
await program.rpc.createFoo({
accounts: {
foo: foo.publicKey,
@ -20,70 +20,73 @@ describe('zero-copy', () => {
},
instructions: [await program.account.foo.createInstruction(foo)],
signers: [foo],
})
const account = await program.account.foo.fetch(foo.publicKey)
});
const account = await program.account.foo.fetch(foo.publicKey);
assert.ok(
JSON.stringify(account.authority.toBuffer()) ===
JSON.stringify(program.provider.wallet.publicKey.toBuffer())
)
assert.ok(account.data.toNumber() === 0)
assert.ok(account.secondData.toNumber() === 0)
);
assert.ok(account.data.toNumber() === 0);
assert.ok(account.secondData.toNumber() === 0);
assert.ok(
JSON.stringify(account.secondAuthority) ===
JSON.stringify([...program.provider.wallet.publicKey.toBuffer()])
)
})
);
});
it('Updates a zero copy account field', async () => {
it("Updates a zero copy account field", async () => {
await program.rpc.updateFoo(new BN(1234), {
accounts: {
foo: foo.publicKey,
authority: program.provider.wallet.publicKey,
},
})
});
const account = await program.account.foo.fetch(foo.publicKey)
const account = await program.account.foo.fetch(foo.publicKey);
assert.ok(
JSON.stringify(account.authority.toBuffer()) ===
JSON.stringify(program.provider.wallet.publicKey.toBuffer())
)
assert.ok(account.data.toNumber() === 1234)
assert.ok(account.secondData.toNumber() === 0)
);
assert.ok(account.data.toNumber() === 1234);
assert.ok(account.secondData.toNumber() === 0);
assert.ok(
JSON.stringify(account.secondAuthority) ===
JSON.stringify([...program.provider.wallet.publicKey.toBuffer()])
)
})
);
});
it('Updates a a second zero copy account field', async () => {
it("Updates a a second zero copy account field", async () => {
await program.rpc.updateFooSecond(new BN(55), {
accounts: {
foo: foo.publicKey,
secondAuthority: program.provider.wallet.publicKey,
},
})
});
const account = await program.account.foo.fetch(foo.publicKey)
const account = await program.account.foo.fetch(foo.publicKey);
assert.ok(
JSON.stringify(account.authority.toBuffer()) ===
JSON.stringify(program.provider.wallet.publicKey.toBuffer())
)
assert.ok(account.data.toNumber() === 1234)
assert.ok(account.secondData.toNumber() === 55)
);
assert.ok(account.data.toNumber() === 1234);
assert.ok(account.secondData.toNumber() === 55);
assert.ok(
JSON.stringify(account.secondAuthority) ===
JSON.stringify([...program.provider.wallet.publicKey.toBuffer()])
)
})
);
});
it('Creates an associated zero copy account', async () => {
it("Creates an associated zero copy account", async () => {
await program.rpc.createBar({
accounts: {
bar: (
await PublicKey.findProgramAddress(
[program.provider.wallet.publicKey.toBuffer(), foo.publicKey.toBuffer()],
[
program.provider.wallet.publicKey.toBuffer(),
foo.publicKey.toBuffer(),
],
program.programId
)
)[0],
@ -91,36 +94,42 @@ describe('zero-copy', () => {
foo: foo.publicKey,
systemProgram: anchor.web3.SystemProgram.programId,
},
})
});
const bar = (
await PublicKey.findProgramAddress(
[program.provider.wallet.publicKey.toBuffer(), foo.publicKey.toBuffer()],
[
program.provider.wallet.publicKey.toBuffer(),
foo.publicKey.toBuffer(),
],
program.programId
)
)[0]
const barAccount = await program.account.bar.fetch(bar)
assert.ok(barAccount.authority.equals(program.provider.wallet.publicKey))
assert.ok(barAccount.data.toNumber() === 0)
})
)[0];
const barAccount = await program.account.bar.fetch(bar);
assert.ok(barAccount.authority.equals(program.provider.wallet.publicKey));
assert.ok(barAccount.data.toNumber() === 0);
});
it('Updates an associated zero copy account', async () => {
it("Updates an associated zero copy account", async () => {
const bar = (
await PublicKey.findProgramAddress(
[program.provider.wallet.publicKey.toBuffer(), foo.publicKey.toBuffer()],
[
program.provider.wallet.publicKey.toBuffer(),
foo.publicKey.toBuffer(),
],
program.programId
)
)[0]
)[0];
await program.rpc.updateBar(new BN(99), {
accounts: {
bar,
authority: program.provider.wallet.publicKey,
foo: foo.publicKey,
},
})
const barAccount = await program.account.bar.fetch(bar)
assert.ok(barAccount.authority.equals(program.provider.wallet.publicKey))
assert.ok(barAccount.data.toNumber() === 99)
});
const barAccount = await program.account.bar.fetch(bar);
assert.ok(barAccount.authority.equals(program.provider.wallet.publicKey));
assert.ok(barAccount.data.toNumber() === 99);
// Check zero_copy CPI
await programCpi.rpc.checkCpi(new BN(1337), {
accounts: {
@ -129,52 +138,56 @@ describe('zero-copy', () => {
foo: foo.publicKey,
zeroCopyProgram: program.programId,
},
})
const barAccountAfterCpi = await program.account.bar.fetch(bar)
assert.ok(barAccountAfterCpi.authority.equals(program.provider.wallet.publicKey))
assert.ok(barAccountAfterCpi.data.toNumber() === 1337)
})
});
const barAccountAfterCpi = await program.account.bar.fetch(bar);
assert.ok(
barAccountAfterCpi.authority.equals(program.provider.wallet.publicKey)
);
assert.ok(barAccountAfterCpi.data.toNumber() === 1337);
});
const eventQ = anchor.web3.Keypair.generate()
const size = 1000000 + 8 // Account size in bytes.
const eventQ = anchor.web3.Keypair.generate();
const size = 1000000 + 8; // Account size in bytes.
it('Creates a large event queue', async () => {
it("Creates a large event queue", async () => {
await program.rpc.createLargeAccount({
accounts: {
eventQ: eventQ.publicKey,
rent: anchor.web3.SYSVAR_RENT_PUBKEY,
},
instructions: [await program.account.eventQ.createInstruction(eventQ, size)],
instructions: [
await program.account.eventQ.createInstruction(eventQ, size),
],
signers: [eventQ],
})
const account = await program.account.eventQ.fetch(eventQ.publicKey)
assert.ok(account.events.length === 25000)
});
const account = await program.account.eventQ.fetch(eventQ.publicKey);
assert.ok(account.events.length === 25000);
account.events.forEach((event) => {
assert.ok(event.from.equals(PublicKey.default))
assert.ok(event.data.toNumber() === 0)
})
})
assert.ok(event.from.equals(PublicKey.default));
assert.ok(event.data.toNumber() === 0);
});
});
it('Updates a large event queue', async () => {
it("Updates a large event queue", async () => {
// Set index 0.
await program.rpc.updateLargeAccount(0, new BN(48), {
accounts: {
eventQ: eventQ.publicKey,
from: program.provider.wallet.publicKey,
},
})
});
// Verify update.
let account = await program.account.eventQ.fetch(eventQ.publicKey)
assert.ok(account.events.length === 25000)
let account = await program.account.eventQ.fetch(eventQ.publicKey);
assert.ok(account.events.length === 25000);
account.events.forEach((event, idx) => {
if (idx === 0) {
assert.ok(event.from.equals(program.provider.wallet.publicKey))
assert.ok(event.data.toNumber() === 48)
assert.ok(event.from.equals(program.provider.wallet.publicKey));
assert.ok(event.data.toNumber() === 48);
} else {
assert.ok(event.from.equals(PublicKey.default))
assert.ok(event.data.toNumber() === 0)
assert.ok(event.from.equals(PublicKey.default));
assert.ok(event.data.toNumber() === 0);
}
})
});
// Set index 11111.
await program.rpc.updateLargeAccount(11111, new BN(1234), {
@ -182,22 +195,22 @@ describe('zero-copy', () => {
eventQ: eventQ.publicKey,
from: program.provider.wallet.publicKey,
},
})
});
// Verify update.
account = await program.account.eventQ.fetch(eventQ.publicKey)
assert.ok(account.events.length === 25000)
account = await program.account.eventQ.fetch(eventQ.publicKey);
assert.ok(account.events.length === 25000);
account.events.forEach((event, idx) => {
if (idx === 0) {
assert.ok(event.from.equals(program.provider.wallet.publicKey))
assert.ok(event.data.toNumber() === 48)
assert.ok(event.from.equals(program.provider.wallet.publicKey));
assert.ok(event.data.toNumber() === 48);
} else if (idx === 11111) {
assert.ok(event.from.equals(program.provider.wallet.publicKey))
assert.ok(event.data.toNumber() === 1234)
assert.ok(event.from.equals(program.provider.wallet.publicKey));
assert.ok(event.data.toNumber() === 1234);
} else {
assert.ok(event.from.equals(PublicKey.default))
assert.ok(event.data.toNumber() === 0)
assert.ok(event.from.equals(PublicKey.default));
assert.ok(event.data.toNumber() === 0);
}
})
});
// Set last index.
await program.rpc.updateLargeAccount(24999, new BN(99), {
@ -205,28 +218,28 @@ describe('zero-copy', () => {
eventQ: eventQ.publicKey,
from: program.provider.wallet.publicKey,
},
})
});
// Verify update.
account = await program.account.eventQ.fetch(eventQ.publicKey)
assert.ok(account.events.length === 25000)
account = await program.account.eventQ.fetch(eventQ.publicKey);
assert.ok(account.events.length === 25000);
account.events.forEach((event, idx) => {
if (idx === 0) {
assert.ok(event.from.equals(program.provider.wallet.publicKey))
assert.ok(event.data.toNumber() === 48)
assert.ok(event.from.equals(program.provider.wallet.publicKey));
assert.ok(event.data.toNumber() === 48);
} else if (idx === 11111) {
assert.ok(event.from.equals(program.provider.wallet.publicKey))
assert.ok(event.data.toNumber() === 1234)
assert.ok(event.from.equals(program.provider.wallet.publicKey));
assert.ok(event.data.toNumber() === 1234);
} else if (idx === 24999) {
assert.ok(event.from.equals(program.provider.wallet.publicKey))
assert.ok(event.data.toNumber() === 99)
assert.ok(event.from.equals(program.provider.wallet.publicKey));
assert.ok(event.data.toNumber() === 99);
} else {
assert.ok(event.from.equals(PublicKey.default))
assert.ok(event.data.toNumber() === 0)
assert.ok(event.from.equals(PublicKey.default));
assert.ok(event.data.toNumber() === 0);
}
})
})
});
});
it('Errors when setting an out of bounds index', async () => {
it("Errors when setting an out of bounds index", async () => {
// Fail to set non existing index.
await assert.rejects(
async () => {
@ -235,12 +248,12 @@ describe('zero-copy', () => {
eventQ: eventQ.publicKey,
from: program.provider.wallet.publicKey,
},
})
});
},
(err) => {
console.log('err', err)
return true
console.log("err", err);
return true;
}
)
})
})
);
});
});