How to use instruction method in wpt

Best JavaScript code snippet using wpt

system-program.ts

Source:system-program.ts Github

copy

Full Screen

1import * as BufferLayout from '@gemachain/buffer-layout';2import {encodeData, decodeData, InstructionType} from './instruction';3import * as Layout from './layout';4import {NONCE_ACCOUNT_LENGTH} from './nonce-account';5import {PublicKey} from './publickey';6import {SYSVAR_RECENT_BLOCKHASHES_PUBKEY, SYSVAR_RENT_PUBKEY} from './sysvar';7import {Transaction, TransactionInstruction} from './transaction';8import {toBuffer} from './util/to-buffer';9/**10 * Create account system transaction params11 */12export type CreateAccountParams = {13 /** The account that will transfer carats to the created account */14 fromPubkey: PublicKey;15 /** Public key of the created account */16 newAccountPubkey: PublicKey;17 /** Amount of carats to transfer to the created account */18 carats: number;19 /** Amount of space in bytes to allocate to the created account */20 space: number;21 /** Public key of the program to assign as the owner of the created account */22 programId: PublicKey;23};24/**25 * Transfer system transaction params26 */27export type TransferParams = {28 /** Account that will transfer carats */29 fromPubkey: PublicKey;30 /** Account that will receive transferred carats */31 toPubkey: PublicKey;32 /** Amount of carats to transfer */33 carats: number;34};35/**36 * Assign system transaction params37 */38export type AssignParams = {39 /** Public key of the account which will be assigned a new owner */40 accountPubkey: PublicKey;41 /** Public key of the program to assign as the owner */42 programId: PublicKey;43};44/**45 * Create account with seed system transaction params46 */47export type CreateAccountWithSeedParams = {48 /** The account that will transfer carats to the created account */49 fromPubkey: PublicKey;50 /** Public key of the created account. Must be pre-calculated with PublicKey.createWithSeed() */51 newAccountPubkey: PublicKey;52 /** Base public key to use to derive the address of the created account. Must be the same as the base key used to create `newAccountPubkey` */53 basePubkey: PublicKey;54 /** Seed to use to derive the address of the created account. Must be the same as the seed used to create `newAccountPubkey` */55 seed: string;56 /** Amount of carats to transfer to the created account */57 carats: number;58 /** Amount of space in bytes to allocate to the created account */59 space: number;60 /** Public key of the program to assign as the owner of the created account */61 programId: PublicKey;62};63/**64 * Create nonce account system transaction params65 */66export type CreateNonceAccountParams = {67 /** The account that will transfer carats to the created nonce account */68 fromPubkey: PublicKey;69 /** Public key of the created nonce account */70 noncePubkey: PublicKey;71 /** Public key to set as authority of the created nonce account */72 authorizedPubkey: PublicKey;73 /** Amount of carats to transfer to the created nonce account */74 carats: number;75};76/**77 * Create nonce account with seed system transaction params78 */79export type CreateNonceAccountWithSeedParams = {80 /** The account that will transfer carats to the created nonce account */81 fromPubkey: PublicKey;82 /** Public key of the created nonce account */83 noncePubkey: PublicKey;84 /** Public key to set as authority of the created nonce account */85 authorizedPubkey: PublicKey;86 /** Amount of carats to transfer to the created nonce account */87 carats: number;88 /** Base public key to use to derive the address of the nonce account */89 basePubkey: PublicKey;90 /** Seed to use to derive the address of the nonce account */91 seed: string;92};93/**94 * Initialize nonce account system instruction params95 */96export type InitializeNonceParams = {97 /** Nonce account which will be initialized */98 noncePubkey: PublicKey;99 /** Public key to set as authority of the initialized nonce account */100 authorizedPubkey: PublicKey;101};102/**103 * Advance nonce account system instruction params104 */105export type AdvanceNonceParams = {106 /** Nonce account */107 noncePubkey: PublicKey;108 /** Public key of the nonce authority */109 authorizedPubkey: PublicKey;110};111/**112 * Withdraw nonce account system transaction params113 */114export type WithdrawNonceParams = {115 /** Nonce account */116 noncePubkey: PublicKey;117 /** Public key of the nonce authority */118 authorizedPubkey: PublicKey;119 /** Public key of the account which will receive the withdrawn nonce account balance */120 toPubkey: PublicKey;121 /** Amount of carats to withdraw from the nonce account */122 carats: number;123};124/**125 * Authorize nonce account system transaction params126 */127export type AuthorizeNonceParams = {128 /** Nonce account */129 noncePubkey: PublicKey;130 /** Public key of the current nonce authority */131 authorizedPubkey: PublicKey;132 /** Public key to set as the new nonce authority */133 newAuthorizedPubkey: PublicKey;134};135/**136 * Allocate account system transaction params137 */138export type AllocateParams = {139 /** Account to allocate */140 accountPubkey: PublicKey;141 /** Amount of space in bytes to allocate */142 space: number;143};144/**145 * Allocate account with seed system transaction params146 */147export type AllocateWithSeedParams = {148 /** Account to allocate */149 accountPubkey: PublicKey;150 /** Base public key to use to derive the address of the allocated account */151 basePubkey: PublicKey;152 /** Seed to use to derive the address of the allocated account */153 seed: string;154 /** Amount of space in bytes to allocate */155 space: number;156 /** Public key of the program to assign as the owner of the allocated account */157 programId: PublicKey;158};159/**160 * Assign account with seed system transaction params161 */162export type AssignWithSeedParams = {163 /** Public key of the account which will be assigned a new owner */164 accountPubkey: PublicKey;165 /** Base public key to use to derive the address of the assigned account */166 basePubkey: PublicKey;167 /** Seed to use to derive the address of the assigned account */168 seed: string;169 /** Public key of the program to assign as the owner */170 programId: PublicKey;171};172/**173 * Transfer with seed system transaction params174 */175export type TransferWithSeedParams = {176 /** Account that will transfer carats */177 fromPubkey: PublicKey;178 /** Base public key to use to derive the funding account address */179 basePubkey: PublicKey;180 /** Account that will receive transferred carats */181 toPubkey: PublicKey;182 /** Amount of carats to transfer */183 carats: number;184 /** Seed to use to derive the funding account address */185 seed: string;186 /** Program id to use to derive the funding account address */187 programId: PublicKey;188};189/**190 * System Instruction class191 */192export class SystemInstruction {193 /**194 * @internal195 */196 constructor() {}197 /**198 * Decode a system instruction and retrieve the instruction type.199 */200 static decodeInstructionType(201 instruction: TransactionInstruction,202 ): SystemInstructionType {203 this.checkProgramId(instruction.programId);204 const instructionTypeLayout = BufferLayout.u32('instruction');205 const typeIndex = instructionTypeLayout.decode(instruction.data);206 let type: SystemInstructionType | undefined;207 for (const [ixType, layout] of Object.entries(SYSTEM_INSTRUCTION_LAYOUTS)) {208 if (layout.index == typeIndex) {209 type = ixType as SystemInstructionType;210 break;211 }212 }213 if (!type) {214 throw new Error('Instruction type incorrect; not a SystemInstruction');215 }216 return type;217 }218 /**219 * Decode a create account system instruction and retrieve the instruction params.220 */221 static decodeCreateAccount(222 instruction: TransactionInstruction,223 ): CreateAccountParams {224 this.checkProgramId(instruction.programId);225 this.checkKeyLength(instruction.keys, 2);226 const {carats, space, programId} = decodeData(227 SYSTEM_INSTRUCTION_LAYOUTS.Create,228 instruction.data,229 );230 return {231 fromPubkey: instruction.keys[0].pubkey,232 newAccountPubkey: instruction.keys[1].pubkey,233 carats,234 space,235 programId: new PublicKey(programId),236 };237 }238 /**239 * Decode a transfer system instruction and retrieve the instruction params.240 */241 static decodeTransfer(instruction: TransactionInstruction): TransferParams {242 this.checkProgramId(instruction.programId);243 this.checkKeyLength(instruction.keys, 2);244 const {carats} = decodeData(245 SYSTEM_INSTRUCTION_LAYOUTS.Transfer,246 instruction.data,247 );248 return {249 fromPubkey: instruction.keys[0].pubkey,250 toPubkey: instruction.keys[1].pubkey,251 carats,252 };253 }254 /**255 * Decode a transfer with seed system instruction and retrieve the instruction params.256 */257 static decodeTransferWithSeed(258 instruction: TransactionInstruction,259 ): TransferWithSeedParams {260 this.checkProgramId(instruction.programId);261 this.checkKeyLength(instruction.keys, 3);262 const {carats, seed, programId} = decodeData(263 SYSTEM_INSTRUCTION_LAYOUTS.TransferWithSeed,264 instruction.data,265 );266 return {267 fromPubkey: instruction.keys[0].pubkey,268 basePubkey: instruction.keys[1].pubkey,269 toPubkey: instruction.keys[2].pubkey,270 carats,271 seed,272 programId: new PublicKey(programId),273 };274 }275 /**276 * Decode an allocate system instruction and retrieve the instruction params.277 */278 static decodeAllocate(instruction: TransactionInstruction): AllocateParams {279 this.checkProgramId(instruction.programId);280 this.checkKeyLength(instruction.keys, 1);281 const {space} = decodeData(282 SYSTEM_INSTRUCTION_LAYOUTS.Allocate,283 instruction.data,284 );285 return {286 accountPubkey: instruction.keys[0].pubkey,287 space,288 };289 }290 /**291 * Decode an allocate with seed system instruction and retrieve the instruction params.292 */293 static decodeAllocateWithSeed(294 instruction: TransactionInstruction,295 ): AllocateWithSeedParams {296 this.checkProgramId(instruction.programId);297 this.checkKeyLength(instruction.keys, 1);298 const {base, seed, space, programId} = decodeData(299 SYSTEM_INSTRUCTION_LAYOUTS.AllocateWithSeed,300 instruction.data,301 );302 return {303 accountPubkey: instruction.keys[0].pubkey,304 basePubkey: new PublicKey(base),305 seed,306 space,307 programId: new PublicKey(programId),308 };309 }310 /**311 * Decode an assign system instruction and retrieve the instruction params.312 */313 static decodeAssign(instruction: TransactionInstruction): AssignParams {314 this.checkProgramId(instruction.programId);315 this.checkKeyLength(instruction.keys, 1);316 const {programId} = decodeData(317 SYSTEM_INSTRUCTION_LAYOUTS.Assign,318 instruction.data,319 );320 return {321 accountPubkey: instruction.keys[0].pubkey,322 programId: new PublicKey(programId),323 };324 }325 /**326 * Decode an assign with seed system instruction and retrieve the instruction params.327 */328 static decodeAssignWithSeed(329 instruction: TransactionInstruction,330 ): AssignWithSeedParams {331 this.checkProgramId(instruction.programId);332 this.checkKeyLength(instruction.keys, 1);333 const {base, seed, programId} = decodeData(334 SYSTEM_INSTRUCTION_LAYOUTS.AssignWithSeed,335 instruction.data,336 );337 return {338 accountPubkey: instruction.keys[0].pubkey,339 basePubkey: new PublicKey(base),340 seed,341 programId: new PublicKey(programId),342 };343 }344 /**345 * Decode a create account with seed system instruction and retrieve the instruction params.346 */347 static decodeCreateWithSeed(348 instruction: TransactionInstruction,349 ): CreateAccountWithSeedParams {350 this.checkProgramId(instruction.programId);351 this.checkKeyLength(instruction.keys, 2);352 const {base, seed, carats, space, programId} = decodeData(353 SYSTEM_INSTRUCTION_LAYOUTS.CreateWithSeed,354 instruction.data,355 );356 return {357 fromPubkey: instruction.keys[0].pubkey,358 newAccountPubkey: instruction.keys[1].pubkey,359 basePubkey: new PublicKey(base),360 seed,361 carats,362 space,363 programId: new PublicKey(programId),364 };365 }366 /**367 * Decode a nonce initialize system instruction and retrieve the instruction params.368 */369 static decodeNonceInitialize(370 instruction: TransactionInstruction,371 ): InitializeNonceParams {372 this.checkProgramId(instruction.programId);373 this.checkKeyLength(instruction.keys, 3);374 const {authorized} = decodeData(375 SYSTEM_INSTRUCTION_LAYOUTS.InitializeNonceAccount,376 instruction.data,377 );378 return {379 noncePubkey: instruction.keys[0].pubkey,380 authorizedPubkey: new PublicKey(authorized),381 };382 }383 /**384 * Decode a nonce advance system instruction and retrieve the instruction params.385 */386 static decodeNonceAdvance(387 instruction: TransactionInstruction,388 ): AdvanceNonceParams {389 this.checkProgramId(instruction.programId);390 this.checkKeyLength(instruction.keys, 3);391 decodeData(392 SYSTEM_INSTRUCTION_LAYOUTS.AdvanceNonceAccount,393 instruction.data,394 );395 return {396 noncePubkey: instruction.keys[0].pubkey,397 authorizedPubkey: instruction.keys[2].pubkey,398 };399 }400 /**401 * Decode a nonce withdraw system instruction and retrieve the instruction params.402 */403 static decodeNonceWithdraw(404 instruction: TransactionInstruction,405 ): WithdrawNonceParams {406 this.checkProgramId(instruction.programId);407 this.checkKeyLength(instruction.keys, 5);408 const {carats} = decodeData(409 SYSTEM_INSTRUCTION_LAYOUTS.WithdrawNonceAccount,410 instruction.data,411 );412 return {413 noncePubkey: instruction.keys[0].pubkey,414 toPubkey: instruction.keys[1].pubkey,415 authorizedPubkey: instruction.keys[4].pubkey,416 carats,417 };418 }419 /**420 * Decode a nonce authorize system instruction and retrieve the instruction params.421 */422 static decodeNonceAuthorize(423 instruction: TransactionInstruction,424 ): AuthorizeNonceParams {425 this.checkProgramId(instruction.programId);426 this.checkKeyLength(instruction.keys, 2);427 const {authorized} = decodeData(428 SYSTEM_INSTRUCTION_LAYOUTS.AuthorizeNonceAccount,429 instruction.data,430 );431 return {432 noncePubkey: instruction.keys[0].pubkey,433 authorizedPubkey: instruction.keys[1].pubkey,434 newAuthorizedPubkey: new PublicKey(authorized),435 };436 }437 /**438 * @internal439 */440 static checkProgramId(programId: PublicKey) {441 if (!programId.equals(SystemProgram.programId)) {442 throw new Error('invalid instruction; programId is not SystemProgram');443 }444 }445 /**446 * @internal447 */448 static checkKeyLength(keys: Array<any>, expectedLength: number) {449 if (keys.length < expectedLength) {450 throw new Error(451 `invalid instruction; found ${keys.length} keys, expected at least ${expectedLength}`,452 );453 }454 }455}456/**457 * An enumeration of valid SystemInstructionType's458 */459export type SystemInstructionType =460 | 'AdvanceNonceAccount'461 | 'Allocate'462 | 'AllocateWithSeed'463 | 'Assign'464 | 'AssignWithSeed'465 | 'AuthorizeNonceAccount'466 | 'Create'467 | 'CreateWithSeed'468 | 'InitializeNonceAccount'469 | 'Transfer'470 | 'TransferWithSeed'471 | 'WithdrawNonceAccount';472/**473 * An enumeration of valid system InstructionType's474 * @internal475 */476export const SYSTEM_INSTRUCTION_LAYOUTS: {477 [type in SystemInstructionType]: InstructionType;478} = Object.freeze({479 Create: {480 index: 0,481 layout: BufferLayout.struct([482 BufferLayout.u32('instruction'),483 BufferLayout.ns64('carats'),484 BufferLayout.ns64('space'),485 Layout.publicKey('programId'),486 ]),487 },488 Assign: {489 index: 1,490 layout: BufferLayout.struct([491 BufferLayout.u32('instruction'),492 Layout.publicKey('programId'),493 ]),494 },495 Transfer: {496 index: 2,497 layout: BufferLayout.struct([498 BufferLayout.u32('instruction'),499 BufferLayout.ns64('carats'),500 ]),501 },502 CreateWithSeed: {503 index: 3,504 layout: BufferLayout.struct([505 BufferLayout.u32('instruction'),506 Layout.publicKey('base'),507 Layout.rustString('seed'),508 BufferLayout.ns64('carats'),509 BufferLayout.ns64('space'),510 Layout.publicKey('programId'),511 ]),512 },513 AdvanceNonceAccount: {514 index: 4,515 layout: BufferLayout.struct([BufferLayout.u32('instruction')]),516 },517 WithdrawNonceAccount: {518 index: 5,519 layout: BufferLayout.struct([520 BufferLayout.u32('instruction'),521 BufferLayout.ns64('carats'),522 ]),523 },524 InitializeNonceAccount: {525 index: 6,526 layout: BufferLayout.struct([527 BufferLayout.u32('instruction'),528 Layout.publicKey('authorized'),529 ]),530 },531 AuthorizeNonceAccount: {532 index: 7,533 layout: BufferLayout.struct([534 BufferLayout.u32('instruction'),535 Layout.publicKey('authorized'),536 ]),537 },538 Allocate: {539 index: 8,540 layout: BufferLayout.struct([541 BufferLayout.u32('instruction'),542 BufferLayout.ns64('space'),543 ]),544 },545 AllocateWithSeed: {546 index: 9,547 layout: BufferLayout.struct([548 BufferLayout.u32('instruction'),549 Layout.publicKey('base'),550 Layout.rustString('seed'),551 BufferLayout.ns64('space'),552 Layout.publicKey('programId'),553 ]),554 },555 AssignWithSeed: {556 index: 10,557 layout: BufferLayout.struct([558 BufferLayout.u32('instruction'),559 Layout.publicKey('base'),560 Layout.rustString('seed'),561 Layout.publicKey('programId'),562 ]),563 },564 TransferWithSeed: {565 index: 11,566 layout: BufferLayout.struct([567 BufferLayout.u32('instruction'),568 BufferLayout.ns64('carats'),569 Layout.rustString('seed'),570 Layout.publicKey('programId'),571 ]),572 },573});574/**575 * Factory class for transactions to interact with the System program576 */577export class SystemProgram {578 /**579 * @internal580 */581 constructor() {}582 /**583 * Public key that identifies the System program584 */585 static programId: PublicKey = new PublicKey(586 '11111111111111111111111111111111',587 );588 /**589 * Generate a transaction instruction that creates a new account590 */591 static createAccount(params: CreateAccountParams): TransactionInstruction {592 const type = SYSTEM_INSTRUCTION_LAYOUTS.Create;593 const data = encodeData(type, {594 carats: params.carats,595 space: params.space,596 programId: toBuffer(params.programId.toBuffer()),597 });598 return new TransactionInstruction({599 keys: [600 {pubkey: params.fromPubkey, isSigner: true, isWritable: true},601 {pubkey: params.newAccountPubkey, isSigner: true, isWritable: true},602 ],603 programId: this.programId,604 data,605 });606 }607 /**608 * Generate a transaction instruction that transfers carats from one account to another609 */610 static transfer(611 params: TransferParams | TransferWithSeedParams,612 ): TransactionInstruction {613 let data;614 let keys;615 if ('basePubkey' in params) {616 const type = SYSTEM_INSTRUCTION_LAYOUTS.TransferWithSeed;617 data = encodeData(type, {618 carats: params.carats,619 seed: params.seed,620 programId: toBuffer(params.programId.toBuffer()),621 });622 keys = [623 {pubkey: params.fromPubkey, isSigner: false, isWritable: true},624 {pubkey: params.basePubkey, isSigner: true, isWritable: false},625 {pubkey: params.toPubkey, isSigner: false, isWritable: true},626 ];627 } else {628 const type = SYSTEM_INSTRUCTION_LAYOUTS.Transfer;629 data = encodeData(type, {carats: params.carats});630 keys = [631 {pubkey: params.fromPubkey, isSigner: true, isWritable: true},632 {pubkey: params.toPubkey, isSigner: false, isWritable: true},633 ];634 }635 return new TransactionInstruction({636 keys,637 programId: this.programId,638 data,639 });640 }641 /**642 * Generate a transaction instruction that assigns an account to a program643 */644 static assign(645 params: AssignParams | AssignWithSeedParams,646 ): TransactionInstruction {647 let data;648 let keys;649 if ('basePubkey' in params) {650 const type = SYSTEM_INSTRUCTION_LAYOUTS.AssignWithSeed;651 data = encodeData(type, {652 base: toBuffer(params.basePubkey.toBuffer()),653 seed: params.seed,654 programId: toBuffer(params.programId.toBuffer()),655 });656 keys = [657 {pubkey: params.accountPubkey, isSigner: false, isWritable: true},658 {pubkey: params.basePubkey, isSigner: true, isWritable: false},659 ];660 } else {661 const type = SYSTEM_INSTRUCTION_LAYOUTS.Assign;662 data = encodeData(type, {663 programId: toBuffer(params.programId.toBuffer()),664 });665 keys = [{pubkey: params.accountPubkey, isSigner: true, isWritable: true}];666 }667 return new TransactionInstruction({668 keys,669 programId: this.programId,670 data,671 });672 }673 /**674 * Generate a transaction instruction that creates a new account at675 * an address generated with `from`, a seed, and programId676 */677 static createAccountWithSeed(678 params: CreateAccountWithSeedParams,679 ): TransactionInstruction {680 const type = SYSTEM_INSTRUCTION_LAYOUTS.CreateWithSeed;681 const data = encodeData(type, {682 base: toBuffer(params.basePubkey.toBuffer()),683 seed: params.seed,684 carats: params.carats,685 space: params.space,686 programId: toBuffer(params.programId.toBuffer()),687 });688 let keys = [689 {pubkey: params.fromPubkey, isSigner: true, isWritable: true},690 {pubkey: params.newAccountPubkey, isSigner: false, isWritable: true},691 ];692 if (params.basePubkey != params.fromPubkey) {693 keys.push({pubkey: params.basePubkey, isSigner: true, isWritable: false});694 }695 return new TransactionInstruction({696 keys,697 programId: this.programId,698 data,699 });700 }701 /**702 * Generate a transaction that creates a new Nonce account703 */704 static createNonceAccount(705 params: CreateNonceAccountParams | CreateNonceAccountWithSeedParams,706 ): Transaction {707 const transaction = new Transaction();708 if ('basePubkey' in params && 'seed' in params) {709 transaction.add(710 SystemProgram.createAccountWithSeed({711 fromPubkey: params.fromPubkey,712 newAccountPubkey: params.noncePubkey,713 basePubkey: params.basePubkey,714 seed: params.seed,715 carats: params.carats,716 space: NONCE_ACCOUNT_LENGTH,717 programId: this.programId,718 }),719 );720 } else {721 transaction.add(722 SystemProgram.createAccount({723 fromPubkey: params.fromPubkey,724 newAccountPubkey: params.noncePubkey,725 carats: params.carats,726 space: NONCE_ACCOUNT_LENGTH,727 programId: this.programId,728 }),729 );730 }731 const initParams = {732 noncePubkey: params.noncePubkey,733 authorizedPubkey: params.authorizedPubkey,734 };735 transaction.add(this.nonceInitialize(initParams));736 return transaction;737 }738 /**739 * Generate an instruction to initialize a Nonce account740 */741 static nonceInitialize(742 params: InitializeNonceParams,743 ): TransactionInstruction {744 const type = SYSTEM_INSTRUCTION_LAYOUTS.InitializeNonceAccount;745 const data = encodeData(type, {746 authorized: toBuffer(params.authorizedPubkey.toBuffer()),747 });748 const instructionData = {749 keys: [750 {pubkey: params.noncePubkey, isSigner: false, isWritable: true},751 {752 pubkey: SYSVAR_RECENT_BLOCKHASHES_PUBKEY,753 isSigner: false,754 isWritable: false,755 },756 {pubkey: SYSVAR_RENT_PUBKEY, isSigner: false, isWritable: false},757 ],758 programId: this.programId,759 data,760 };761 return new TransactionInstruction(instructionData);762 }763 /**764 * Generate an instruction to advance the nonce in a Nonce account765 */766 static nonceAdvance(params: AdvanceNonceParams): TransactionInstruction {767 const type = SYSTEM_INSTRUCTION_LAYOUTS.AdvanceNonceAccount;768 const data = encodeData(type);769 const instructionData = {770 keys: [771 {pubkey: params.noncePubkey, isSigner: false, isWritable: true},772 {773 pubkey: SYSVAR_RECENT_BLOCKHASHES_PUBKEY,774 isSigner: false,775 isWritable: false,776 },777 {pubkey: params.authorizedPubkey, isSigner: true, isWritable: false},778 ],779 programId: this.programId,780 data,781 };782 return new TransactionInstruction(instructionData);783 }784 /**785 * Generate a transaction instruction that withdraws carats from a Nonce account786 */787 static nonceWithdraw(params: WithdrawNonceParams): TransactionInstruction {788 const type = SYSTEM_INSTRUCTION_LAYOUTS.WithdrawNonceAccount;789 const data = encodeData(type, {carats: params.carats});790 return new TransactionInstruction({791 keys: [792 {pubkey: params.noncePubkey, isSigner: false, isWritable: true},793 {pubkey: params.toPubkey, isSigner: false, isWritable: true},794 {795 pubkey: SYSVAR_RECENT_BLOCKHASHES_PUBKEY,796 isSigner: false,797 isWritable: false,798 },799 {800 pubkey: SYSVAR_RENT_PUBKEY,801 isSigner: false,802 isWritable: false,803 },804 {pubkey: params.authorizedPubkey, isSigner: true, isWritable: false},805 ],806 programId: this.programId,807 data,808 });809 }810 /**811 * Generate a transaction instruction that authorizes a new PublicKey as the authority812 * on a Nonce account.813 */814 static nonceAuthorize(params: AuthorizeNonceParams): TransactionInstruction {815 const type = SYSTEM_INSTRUCTION_LAYOUTS.AuthorizeNonceAccount;816 const data = encodeData(type, {817 authorized: toBuffer(params.newAuthorizedPubkey.toBuffer()),818 });819 return new TransactionInstruction({820 keys: [821 {pubkey: params.noncePubkey, isSigner: false, isWritable: true},822 {pubkey: params.authorizedPubkey, isSigner: true, isWritable: false},823 ],824 programId: this.programId,825 data,826 });827 }828 /**829 * Generate a transaction instruction that allocates space in an account without funding830 */831 static allocate(832 params: AllocateParams | AllocateWithSeedParams,833 ): TransactionInstruction {834 let data;835 let keys;836 if ('basePubkey' in params) {837 const type = SYSTEM_INSTRUCTION_LAYOUTS.AllocateWithSeed;838 data = encodeData(type, {839 base: toBuffer(params.basePubkey.toBuffer()),840 seed: params.seed,841 space: params.space,842 programId: toBuffer(params.programId.toBuffer()),843 });844 keys = [845 {pubkey: params.accountPubkey, isSigner: false, isWritable: true},846 {pubkey: params.basePubkey, isSigner: true, isWritable: false},847 ];848 } else {849 const type = SYSTEM_INSTRUCTION_LAYOUTS.Allocate;850 data = encodeData(type, {851 space: params.space,852 });853 keys = [{pubkey: params.accountPubkey, isSigner: true, isWritable: true}];854 }855 return new TransactionInstruction({856 keys,857 programId: this.programId,858 data,859 });860 }...

Full Screen

Full Screen

solution.ts

Source:solution.ts Github

copy

Full Screen

1import { readFileSync } from 'fs';2class Instruction {3 constructor(direction: string, value: number) {4 this.direction = direction;5 this.value = value;6 }7 direction: string;8 value: number9}10const instructions: Array<Instruction> = readFileSync("day12\\input.txt", "utf-8").split("\r\n").map(x => new Instruction(x.substring(0, 1), parseInt(x.substring(1))));11// Part 112const modulo = (x: number, N: number) => {13 return (x % N + N) % N;14}15const directions = ["N", "E", "S", "W"];16const calculateNextState = (y: number, x: number, facing: string, instruction: Instruction): [number, number, string] => {17 if (instruction.direction === "F") {18 const newPos = calculateNextState(y, x, facing, new Instruction(facing, instruction.value));19 return [newPos[0], newPos[1], facing];20 }21 if (instruction.direction === "L") {22 const newFacing = directions[modulo((directions.indexOf(facing) - instruction.value / (360 / directions.length)), directions.length)];23 return [y, x, newFacing];24 }25 if (instruction.direction === "R") {26 const newFacing = directions[(directions.indexOf(facing) + instruction.value / (360 / directions.length)) % directions.length];27 return [y, x, newFacing];28 }29 if (instruction.direction === "N") {30 return [y - instruction.value, x, facing];31 }32 if (instruction.direction === "E") {33 return [y, x + instruction.value, facing];34 }35 if (instruction.direction === "S") {36 return [y + instruction.value, x, facing];37 }38 if (instruction.direction === "W") {39 return [y, x - instruction.value, facing];40 }41}42const simulateShipMovement = (startingState: [number, number, string]): number => {43 let currentState = startingState;44 for (const instruction of instructions) {45 currentState = calculateNextState(currentState[0], currentState[1], currentState[2], instruction);46 }47 return (Math.abs(currentState[0]) + Math.abs(currentState[1]));48}49console.log("Part 1, Manhattan distance: " + simulateShipMovement([0, 0, "E"]));50const rotatePoint = (point: [number, number], angle: number): [number, number] => {51 const rad = toRadians(angle);52 return [point[0] * Math.cos(rad) + point[1] * Math.sin(rad), point[1] * Math.cos(rad) - point[0] * Math.sin(rad)];53}54const toRadians = (angle: number): number => {55 return angle * (Math.PI / 180);56}57const calculateNextStateWithWaypoint = (shipPos: [number, number], waypointRelativePos: [number, number], instruction: Instruction): [[number, number], [number, number]] => {58 if (instruction.direction === "F") {59 const y = shipPos[0] + waypointRelativePos[0] * instruction.value;60 const x = shipPos[1] + waypointRelativePos[1] * instruction.value;61 return [[y, x], waypointRelativePos];62 }63 if (instruction.direction === "L") {64 return [shipPos, rotatePoint(waypointRelativePos, -instruction.value)];65 }66 if (instruction.direction === "R") {67 return [shipPos, rotatePoint(waypointRelativePos, instruction.value)];68 }69 if (instruction.direction === "N") {70 return [shipPos, [waypointRelativePos[0] - instruction.value, waypointRelativePos[1]]];71 }72 if (instruction.direction === "E") {73 return [shipPos, [waypointRelativePos[0], waypointRelativePos[1] + instruction.value]];74 }75 if (instruction.direction === "S") {76 return [shipPos, [waypointRelativePos[0] + instruction.value, waypointRelativePos[1]]];77 }78 if (instruction.direction === "W") {79 return [shipPos, [waypointRelativePos[0], waypointRelativePos[1] - instruction.value]];80 }81}82const simulateShipMovementWithWaypoint = (shipPosAtStart: [number, number], waypointRelativePosAtStart: [number, number]): number => {83 let ship = shipPosAtStart;84 let waypoint = waypointRelativePosAtStart;85 for (const instruction of instructions) {86 const newState = calculateNextStateWithWaypoint(ship, waypoint, instruction);87 ship = newState[0];88 waypoint = newState[1];89 }90 return (Math.abs(ship[0]) + Math.abs(ship[1]));91}...

Full Screen

Full Screen

instructions.component.ts

Source:instructions.component.ts Github

copy

Full Screen

1import { Component, Input } from '@angular/core';2import { take } from 'rxjs/operators';3import { Instruction } from '../../../shared/models/Instruction';4import { Recipe } from '../../../shared/models/Recipe';5import { InstructionService } from '../../../shared/services/instruction.service';6@Component({7 selector: 'app-instructions',8 templateUrl: './instructions.component.html',9 styleUrls: ['./instructions.component.css']10})11export class InstructionsComponent {12 @Input() recipe: Recipe;13 edit: boolean[] = [];14 instructionInput: string = "";15 @Input('canEdit') canEdit: boolean = false;16 constructor(private instructionService: InstructionService) { }17 addInstruction() {18 let instruction = new Instruction();19 instruction.recipeId = this.recipe.id;20 instruction.instruction = this.instructionInput || "new instruction";21 instruction.instructionOrder = this.recipe.instructionList.length + 1;22 this.instructionService.create(instruction).subscribe(23 res => {24 this.recipe.instructionList.push(res);25 this.instructionInput = "";26 },27 err => {28 console.log(err)29 }30 )31 }32 updateInstruction(input: string, i) {33 // console.log(instruction);34 // console.log(event)35 // console.log(instruction, this.recipe.instructionList[i])36 let updatedInstruction: Instruction = this.recipe.instructionList[i]37 updatedInstruction.instruction = input;38 this.instructionService.update(updatedInstruction).pipe(39 take(1)40 ).subscribe(41 res => {42 this.recipe.instructionList[i] = res;43 this.toggleEdit(i);44 },45 err => {46 }47 )48 }49 toggleEdit(i) {50 this.edit[i] = !this.edit[i];51 }52 deleteInstruction(delIndex, instruction) {53 this.instructionService.delete(instruction.id).pipe(54 take(1)55 ).subscribe(56 res => {57 this.recipe.instructionList.splice(delIndex, 1)58 for (let i = delIndex; i < this.recipe.instructionList.length; i++) {59 this.decrementOrder(this.recipe.instructionList[i])60 }61 },62 err => {63 }64 )65 }66 private decrementOrder(instruction: Instruction) {67 instruction.instructionOrder--;68 this.instructionService.update(instruction).pipe(69 take(1)70 ).subscribe(71 res => {72 }73 )74 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var client = wpt('www.webpagetest.org');3 if (err) return console.error(err);4 console.log('Test started: ' + data.data.testId);5 client.getTestResults(data.data.testId, function(err, data) {6 if (err) return console.error(err);7 console.log(data.data.median.firstView);8 });9});10var wpt = require('webpagetest');11var client = wpt('www.webpagetest.org');12 .then(function(data) {13 console.log('Test started: ' + data.data.testId);14 return client.getTestResults(data.data.testId);15 })16 .then(function(data) {17 console.log(data.data.median.firstView);18 })19 .catch(function(err) {20 console.error(err);21 });

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3wpt.runTest(url, function(err, data) {4 wpt.getTestResults(data.data.testId, function(err, data) {5 console.log(data.data);6 });7});8var wpt = require('webpagetest');9var wpt = new WebPageTest('www.webpagetest.org');10wpt.runTest(url, function(err, data) {11 console.log(data.data);12});13var wpt = require('webpagetest');14var wpt = new WebPageTest('www.webpagetest.org');15wpt.runTest(url, function(err, data) {16 console.log(data.data);17});18var wpt = require('webpagetest');19var wpt = new WebPageTest('www.webpagetest.org');20wpt.runTest(url, function(err, data) {21 console.log(data.data);22});23var wpt = require('webpagetest');24var wpt = new WebPageTest('www.webpagetest.org');25wpt.runTest(url, function(err, data) {26 console.log(data.data);27});

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var test = wpt('www.webpagetest.org');3 if (err) {4 console.log(err);5 } else {6 console.log(data);7 }8});9var wpt = require('webpagetest');10var test = wpt('www.webpagetest.org');11 if (err) {12 console.log(err);13 } else {14 console.log(data);15 }16});17{ [Error: Error: connect ECONNREFUSED

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var test = new wpt('www.webpagetest.org');3test.runTest(url, function(err, data) {4 if (err) return console.error(err);5 test.getTestResults(data.data.testId, function(err, data) {6 if (err) return console.error(err);7 console.log(data.data.median.firstView);8 });9});10{bytesIn: 1419, bytesOut: 489, bytesOutDoc: 489, connections: 5, date: "2015-04-30 14:02:26", docTime: 208, domElements: 19, fullyLoaded: 1143, gzip_savings: 0, gzip_total: 0, image_savings: 0, image_total: 0, images: 0, isResponsive: 0, lastVisualChange: 1143, loadEventEnd: 1143, loadEventStart: 1143, loadTime: 1143, minify_savings: 0, minify_total: 0, minified: 0, optimized: 0, render: 208, requests: 6, requestsDoc: 6, requestsFull: 6, responses_200: 6, responses_404: 0, responses_other: 0, result: 200, score_cache: 100, score_cdn: 100, score_combine: 100, score_compress: 100, score_cookies: 100, score_etags: 100, score_gzip: 100, score_keep-alive: 100, score_minify: 100, score_progressive_jpeg: 100, server_count: 1, server_rtt: 0, speedIndex: 1143, titleTime: 208, TTFB: 206, visualComplete: 1143, visualComplete85: 1143}

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var options = {3};4var client = wpt(options);5 if (err) return console.error(err);6 console.log('Test submitted. Polling for results.');7 client.waitForTestResults(data.data.testId, function(err, data) {8 if (err) return console.error(err);9 console.log('Got test results: %j', data);10 });11});12var wpt = require('webpagetest');13var options = {14};15var client = wpt(options);16 if (err) return console.error(err);17 console.log('Test submitted. Polling for results.');18 client.waitForTestResults(data.data.testId, function(err, data) {19 if (err) return console.error(err);20 console.log('Got test results: %j', data);21 });22});23var wpt = require('webpagetest');24var options = {25};26var client = wpt(options);27 if (err) return console.error(err);28 console.log('Test submitted. Polling for results.');29 client.waitForTestResults(data.data.testId, function(err, data) {30 if (err) return console.error(err);31 console.log('Got test results: %j', data);32 });33});34var wpt = require('webpagetest');35var options = {

Full Screen

Using AI Code Generation

copy

Full Screen

1var wptoolkit = require('wptoolkit');2var wptool = new wptoolkit();3 if (err) {4 console.log(err);5 }6 else {7 console.log(data);8 }9});10var wptoolkit = require('wptoolkit');11var wptool = new wptoolkit();12 if (err) {13 console.log(err);14 }15 else {16 console.log(data);17 }18});19var wptoolkit = require('wptoolkit');20var wptool = new wptoolkit();21 if (err) {22 console.log(err);23 }24 else {25 console.log(data);26 }27});28var wptoolkit = require('wptoolkit');29var wptool = new wptoolkit();30 if (err) {31 console.log(err);32 }33 else {34 console.log(data);35 }36});37var wptoolkit = require('wptoolkit');38var wptool = new wptoolkit();39 if (err) {40 console.log(err);41 }42 else {43 console.log(data);

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run wpt automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful